react父子组件通信
时间: 2023-09-10 21:11:00 浏览: 38
React中,父组件可以通过props传递数据给子组件,子组件可以通过调用父组件传递的函数来向父组件传递数据。
父组件传递数据给子组件:
```
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: "Hello, World!"
};
}
render() {
return (
<div>
<ChildComponent data={this.state.data} />
</div>
);
}
}
class ChildComponent extends React.Component {
render() {
return (
<div>
<p>{this.props.data}</p>
</div>
);
}
}
```
子组件向父组件传递数据:
```
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: ""
};
this.handleData = this.handleData.bind(this);
}
handleData(data) {
this.setState({ data: data });
}
render() {
return (
<div>
<ChildComponent onData={this.handleData} />
<p>Received data: {this.state.data}</p>
</div>
);
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(event) {
this.setState({ input: event.target.value });
}
handleClick() {
this.props.onData(this.state.input);
}
render() {
return (
<div>
<input type="text" value={this.state.input} onChange={this.handleChange} />
<button onClick={this.handleClick}>Send</button>
</div>
);
}
}
```
在上述代码中,子组件中的input和button组件用于接收用户输入的数据,并通过调用父组件传递的onData函数向父组件传递数据。父组件中的handleData函数用于接收子组件传递的数据,并将其存储在父组件的state中,然后渲染到页面上。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)