React中组件间的通信方式

通信场景

  • 父子组件间的通信(父->子,子->父)
  • 兄弟组件间的通信
  • 父组件向后代组件的通信
  • 非关系组件间的通信

父组件向子组件传递

  • 父组件在调用子组件的时候,只需要在子组件标签内传递参数,子组件通过props属性就能接收父组件传递过来的参数
function EmailInput(props) {
    return (
                <label>
                  Email: <input value={props.email} />
                </label>
    );
}

const element = <EmailInput email="123124132@163.com" />;

子组件向父组件传递

  • 子组件向父组件通信的基本思路是,父组件向子组件传一个函数,然后通过这个函数的回调,拿到子组件传过来的值
class Parents extends Component {
  constructor() {
    super();
    this.state = {
      price: 0
    };
  }

  getItemPrice(e) {
    this.setState({
      price: e
    });
  }

  render() {
    return (
      <div>
        <div>price: {this.state.price}</div>
        {/* 向子组件中传入一个函数  */}
        <Child getPrice={this.getItemPrice.bind(this)} />
      </div>
    );
  }
}
class Child extends Component {
  clickGoods(e) {
    // 在此函数中传入值
    this.props.getPrice(e);
  }

  render() {
    return (
      <div>
        <button onClick={this.clickGoods.bind(this, 100)}>goods1</button>
        <button onClick={this.clickGoods.bind(this, 1000)}>goods2</button>
      </div>
    );
  }
}

兄弟组件通信

  • 使用父组件作为中介,相当于从传递信息的组件先向父组件传递数据,再通过父组件传递到接受信息的组件。

跨级通信

  • 可以通过props的方式层层传递,适用于嵌套层级比较浅的时候
  • 使用context,context提供了组件之间通讯的一种方式,可以共享数据,其他数据都能读取对应的数据。
    • 通过使用React.createContext创建一个context
const PriceContext = React.createContext('price')
  • context创建成功后,使用Provider组件创建数据源,使用Consumer组件接收数据
    • Provider组件通过value属性用于给后代组件传递数据
<PriceContext.Provider value={100}>
</PriceContext.Provider>
  • 通过Consumer组件或者或者使用contextType属性接收
<PriceContext.Consumer>
    { /*这里是一个函数*/ }
    {
        price => <div>price:{price}</div>
    }
</PriceContext.Consumer>

非关系组件通信

  • 如果组件之间关系类型比较复杂的情况,建议将数据进行一个全局资源管理,从而实现通信,例如redux。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值