• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

React_11 react组件通信的三种方式

武飞扬头像
阁下何不同风起?
帮助1

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

1.父组件 —> 子组件

步骤:

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

  1.  
    class Parent extends React.Component{
  2.  
    state={
  3.  
    lastName:'张',
  4.  
    firstName:'三',
  5.  
    }
  6.  
    render(){
  7.  
    return (
  8.  
    <div>
  9.  
    传递数据给子组件,<Child lastName={this.state.lastName} />
  10.  
    </div>
  11.  
    )
  12.  
    }
  13.  
    }

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

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

2.子组件 —> 父组件

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

步骤:

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

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

  1.  
    class Parent extends React.Component{
  2.  
    getChildMsg=(msg)=>{
  3.  
    console.log('接收到子组件数据',msg)
  4.  
    }
  5.  
    render(){
  6.  
    return (
  7.  
    <div>
  8.  
    子组件:<Child getMsg={this.getChildMsg}/>
  9.  
    </div>
  10.  
    )
  11.  
    }
  12.  
    }

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

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

  1.  
    class Child extends React.Component{
  2.  
    state={
  3.  
    childMsg:'我是子组件传递过来的数据'
  4.  
    }
  5.  
     
  6.  
    handClick=()=>{
  7.  
    this.props.getMsg(this.state.childMsg)
  8.  
    }
  9.  
     
  10.  
    render(){
  11.  
    return (
  12.  
    <button onClick={this.handClick}>点我发送数据</button>
  13.  
    )
  14.  
    }
  15.  
    }
学新通

3.兄弟组件

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

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

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

  1.  
    // 兄弟组件通信
  2.  
    // 点击子组件Child2似的Child1中数据 1
  3.  
    class Counter extends React.Component{
  4.  
    state={
  5.  
    num:0,
  6.  
    }
  7.  
    handAdd=()=>{
  8.  
    this.setState({
  9.  
    num:this.state.num 1
  10.  
    })
  11.  
    }
  12.  
    render(){
  13.  
    return (
  14.  
    <div>
  15.  
    <Child1 num={this.state.num}></Child1>
  16.  
    <Child2 add={this.handAdd}></Child2>
  17.  
    </div>
  18.  
    )
  19.  
    }
  20.  
    }
  21.  
     
  22.  
    class Child1 extends React.Component{
  23.  
    render(){
  24.  
    return (
  25.  
    <div>
  26.  
    <h1>计数器:{this.props.num}</h1>
  27.  
    </div>
  28.  
    )
  29.  
    }
  30.  
    }
  31.  
    class Child2 extends React.Component{
  32.  
    render(){
  33.  
    return (
  34.  
    <div>
  35.  
    <button onClick={this.props.add}> 1</button>
  36.  
    </div>
  37.  
    )
  38.  
    }
  39.  
    }
  40.  
    ReactDOM.render(<Counter/>,document.getElementById('root'));
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbkacb
系列文章
更多 icon
同类精品
更多 icon
继续加载