美文网首页
react 父子组件修改值

react 父子组件修改值

作者: this_smile | 来源:发表于2019-08-08 17:47 被阅读0次

    父组件

    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>
            )
        }
    }
    

    相关文章

      网友评论

          本文标题:react 父子组件修改值

          本文链接:https://www.haomeiwen.com/subject/gwgxjctx.html