React_11 react组件通信的三种方式

和vue相同,react组件中通信方式也分三种:

1.父组件 —> 子组件

步骤:

1)父组件提供要传递的state数据

class Parent extends React.Component{
    state={
        lastName:张,
        firstName:三,
    }
    render(){
        return (
            <div>
               传递数据给子组件,<Child lastName={this.state.lastName} />
            </div>
        )
    }
}

2)子组件中通过props接收到父组件中传递的数据

function Child(props) { 
    return <div>子组件接收到的数据:{props.lastName}</div>
}

2.子组件 —> 父组件

思路:利用回调函数,父组件提供回调函数,子组件调用,将要传递的数据作为回调函数的参数。

步骤:

1)父组件提供一个回调函数(用于接收数据)

2)将该函数作为属性值传递给子组件

class Parent extends React.Component{
    getChildMsg=(msg)=>{
        console.log(接收到子组件数据,msg)
    }
    render(){
        return (
            <div>
               子组件:<Child getMsg={this.getChildMsg}/>
            </div>
        )
    }
}

3)子组件通过props调用回调函数

4)将子组件的数据作为参数传递给回调函数

class Child extends React.Component{
    state={
        childMsg:我是子组件传递过来的数据
    }

    handClick=()=>{
        this.props.getMsg(this.state.childMsg)
    }

    render(){
        return (
            <button onClick={this.handClick}>点我发送数据</button>
        )
    }
}

3.兄弟组件

思路:将 共享状态提升到最近的公共父组件中,由公共父组件管理这个状态

公共父组件职责:1.提供共享状态;2.提供操作共享状态的方法;

要通讯的子组件只要通过props接收状态或操作状态的方法;

// 兄弟组件通信
// 点击子组件Child2似的Child1中数据+1
class Counter extends React.Component{
    state={
        num:0,
    }
    handAdd=()=>{
        this.setState({
            num:this.state.num+1
        })
    }
    render(){
        return (
            <div>
                <Child1 num={this.state.num}></Child1>
                <Child2 add={this.handAdd}></Child2>
            </div>
        )
    }
}

class Child1 extends React.Component{
    render(){
        return (
            <div>
                <h1>计数器:{this.props.num}</h1>
            </div>
        )
    }
}
class Child2 extends React.Component{
    render(){
        return (
            <div>
                <button onClick={this.props.add}>+1</button>
            </div>
        )
    }
}
ReactDOM.render(<Counter/>,document.getElementById(root));
经验分享 程序员 微信小程序 职场和发展