在 React JS 中,如何告诉父组件子组件中发生了一些事情?



我有一个具有简单层次结构的 React JS 应用程序: ContainingBox 包装了两个 InfoBox 组件。 在这个例子中,我只想告诉 ContainingBox 组件 1( 单击了某些内容,以及 2( 单击了哪个信息框(按标签名称(?

以下是一些在我的浏览器中工作的基本代码,可以启动和运行这个问题。当您单击页面上的信息框元素之一时.log它所做的一切都是控制台。

从本质上讲,我试图实现的是,我希望在单击其中一个子 InfoBox 元素时,ContainingBox 更改状态(特别是呈现的边框颜色(。

我不确定这里的正确方向是什么。

我用 React 16.10.2 构建了这个应用程序,但我很乐意阅读指向我最新的"React 思维方式"的答案。

import React from 'react';
import styled from 'styled-components'
import './App.css';

const StyledInfoBox = styled.div`
width: 100px;
border: solid 1px green;
padding: 10px;
cursor: pointer;
`

class InfoBox extends React.Component {
constructor({blurb}) {
super()
this.state = {
label: (blurb ?  blurb.label : ""),
}
this.selectBox = this.selectBox.bind(this);
}
selectBox(e) {
e.preventDefault()
console.log("selectBox")
// how do I tell the ContainingBox component 1) that something has been clicked,
// and 2) which InfoBox (by label name) has been clicked?
}
render() {
const {label} = this.state
return (
<StyledInfoBox onClick={this.selectBox} >
{label}
</StyledInfoBox>
)
}
}
class ContainingBox extends React.Component {
render() {
return (
<div>
<InfoBox key={1} blurb={{label: "Aenean malesuada lorem"}} />
<InfoBox key={2} blurb={{label: "Lorem Ipsum dor ameet"}} />
</div>
)
}
}
function App() {
return (
<div className="App">
<ContainingBox />
</div>
)
}
export default App;

通过 props 将回调从父组件传递到子组件。

class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
changeNameTo = (newName) => this.setState({name: newName})
render() {
return (
<div>
<h1>{this.state.name}</h1>
<p>
<Child callbackExample={this.changeNameTo} />
</p>
</div>
);
}
}

然后,您就有了子组件。

class Child extends Component {
render() {
return(
<div>
<button onClick={() => this.props.callbackExample("Doggos")}>
Click me
</button>
</div>)
}
}

单击该按钮时,将调用回调设置父项的状态,然后在父项重新呈现时反映该状态。

相关内容

最新更新