父类代码
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Check from './props/Check'
class App extends Component {
constructor(props) {
super(props);
this.childChanged = this.onChildChanged.bind(this);
// this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
val: '0',
dataList:[],
};
}
componentDidMount() {
this.setState((state,props)=>{
return {val:state.val+props.title}
},()=>{
console.log(this.state.val);
})
}
onChildChanged(data) {
// 接收子类传出的方法
console.log(data)
this.setState({
dataList: data
});
}
render() {
return (
<div className="App">
<Check name={'zya'} callbackParent={this.childChanged}>
{ this.state.dataList.map((item,index)=>
<div key={index}>
<h3>name:{item.name}</h3>
<h3>sex:{item.sex}</h3>
</div>
)}
</Check>
</div>
);
}
}
export default App;
子类代码
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Check extends Component{
constructor(props) {
super(props);
this.handleClick = this.testClick.bind(this);
}
testClick(){
const data = new Array({name:'王二',sex:'女'},{name:'张三',sex:'男'});
// 调用父类传来的方法,将数据传给父类
this.props.callbackParent(data)
}
render(){
return (
<div onClick={this.handleClick}>
{this.props.name}
// 将槽点中的子类展示
{this.props.children}
</div>
);
}
}
Check.propTypes = {
name: PropTypes.string
};
Check.defaultProps = {
name: 'Stranger'
};
export default Check;
本文详细介绍了React中如何实现父子组件之间的数据通信。通过具体代码示例,展示了父组件如何接收子组件的数据,并更新状态来反映子组件的变化。这对于理解React组件间通信机制至关重要。
2582

被折叠的 条评论
为什么被折叠?



