父组件
class Father extends React.Component {
constructor(props) {
super(props)
this.state = {
childChangeFather: '当前点击的是:#',
list: [
{id: 1, text: '1'},
{id: 2, text: '2'},
{id: 3, text: '3'}
],
fatherChangeChildData: '父传子:#'
}
}
onChangeState(item) {
this.setState((state) => ({
childChangeFather: '当前点击的是:' + item.text,
fatherChangeChildData: '父传子:' + item.text
}))
}
render() {
return (
<div>
<p>内容:{this.state.childChangeFather}</p>
<Child list={this.state.list} fatherChangeChild={this.state.fatherChangeChildData} onClick={i => this.onChangeState(i)}/>
</div>
)
}
}
子组件
class Child extends React.Component {
componentWillReceiveProps(nextProps){
this.setState({
fatherChangeChildData: nextProps.fatherChangeChild
})
}
render(){
return (
<ul>
{
this.props.list.map((item) => (
<li key={item.id} onClick={() => this.props.onClick(item)}>{item.text}</li>
))
}
<span>{this.props.fatherChangeChild}</span>
</ul>
)
}
}