目录

react 组件通信

react 使用一些心得记录。

父子组件

父子之间通信主要通过 this.props

父->子

通过属性传入,传入如果是变量,当父值改变时子组件值也会改变。
以下将 Fatherdata 传入到 Son 中。

Son:

class Son extends React.Component {
    state = {
        data: 'son',
    }
    // 父传来值改变
    componentWillReceiveProps(nextProps) {
        // 父值改变 this.props.data
        if (nextProps.data && nextProps.data !== this.state.data) {
            this.setState({ data: nextProps.data });
        }
    }
    render() {
        return (
            <a>
                {this.props.data}
            </a>
        );
    }
}
export default Son;

Father:

class Father extends React.Component {
    state = {
        data: 'father',
    }
    render() {
        return (
            <Son
                data = {this.state.data}
            />
        );
    }
}

子->父

我感觉这个类似于函数回调,值传递需要借助这个回调函数。
还是举个例子,Son 中按钮按下动作传递给 Father

Son:

class Son extends React.Component {
    state {
        data: 'son',
    }
    onClick = () => {
        // 回调函数
        if (this.props.onClick) this.props.onClick(this.state.data);
    }
    render() {
        return (
            <Button onClick={this.onClick}>button</Button>
        );
    }
}
export default Son;

Father:

class Father extends React.Component {
    onClick = (value) => {
        console.log("son ->", value)
    }
    render() {
        return (
            <Son
                onClick = {this.onClick}
            />
        );
    }
}