react 父子组件修改值

父组件

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>
        )
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容