组件间通信

18 篇文章 1 订阅

父组件向子组件通信

React中数据的流动是单向的,父组件向子组件的通信是最常见的组件间通信形式,即父组件通过props传递子组件信息。

例如:

class App extends Component{
  
  render(){
    return (
      <div>
        <Controlled inputState="Hello World"/>
      </div>
    )
  }
}

class Controlled extends Component{
  constructor(props){
    super(props);
    this.state = {
      inputState: this.props.inputState
    }
    this.changeHandle = this.changeHandle.bind(this);
  }

  changeHandle(e){
    this.setState({
      inputState: e.target.value.toUpperCase()
    });
  }

  render(){
    const {inputState} = this.state;
    return (
      <div>
        <input type='text' value={inputState} onChange={this.changeHandle}></input>
      </div>
    )
  }
}

可以看出上面的代码中,Controlled子组件通过父组件传入的inputState props获得初值。

子组件向父组件通信

子组件想要向父组件通信通常有有两种方式:

  • 回调函数
  • 利用自定义事件机制

回调函数

class App extends Component{
  constructor(props){
    super(props);
    this.state = {
      inputState: ''
    };
  }
  changeHandle(e){
    this.setState({
      inputState: e.target.value.toUpperCase()
    });
  }

  render(){
    return (
      <div>
        <Controlled inputState={this.state.inputState} changeHandle={this.changeHandle.bind(this)}/>
      </div>
    )
  }
}

class Controlled extends Component{
  constructor(props){
    super(props);
    
    this.changeHandle = this.props.changeHandle;
  }

  render(){
    const {inputState} = this.props;
    return (
      <div>
        <input type='text' value={inputState} onChange={this.changeHandle}></input>
      </div>
    )
  }
}

Controlled子组件中的状态通过由父组件传入的changeHandle回调函数获得,并在父组件中将该状态写回子组件。实现了“跨层级”的数据双向绑定。

利用自定义事件机制

所谓的自定义事件机制就是常见的发布/订阅模式。可以使用Node.js Events模块的浏览器版实现。

class App extends Component{
  constructor(props){
    super(props);
    this.state = {
      inputState: ''
    };
  }
  
  componentDidMount(){
    emitter.addListener('change', (msg)=>{
      this.setState({
        inputState: msg
      });
    });
  }

  componentWillUnmount(){
    emitter.removeAllListeners('change');
  }

  render(){
    return (
      <div>
        <Controlled inputState={this.state.inputState} />
      </div>
    )
  }
}

class Controlled extends Component{
  constructor(props){
    super(props);
    
    this.changeHandle = this.changeHandle.bind(this);
  }

  changeHandle(e){
    emitter.emit('change', e.target.value);
  }

  render(){
    const {inputState} = this.props;
    return (
      <div>
        <input type='text' value={inputState} onChange={this.changeHandle}></input>
      </div>
    )
  }
}

还是实现了跟回调函数例子中相同的功能,只不过使用了自定义事件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值