React 组件通信

父组件到子组件

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      msg: 'msg from parent'
    }
  }

  handleClick(){
    this.setState({
      msg: this.state.msg.split('').reverse().join('')
    })
  }

  render() {
    return (
      <div>
        <h3 onClick={this.handleClick.bind(this)}>我是父组件 => {this.state.msg}</h3>
        <Son msg={this.state.msg} />
      </div>
    )
  }
}

class Son extends Component {
  render() {
    return (
      <h5>我是子组件 => {this.props.msg}</h5>
    )
  }
}

子组件到父组件

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      number: '__'
    }
  }

  getData(data) {
    this.setState({
      number: data
    })
  }

  render() {
    return (
      <div>
        <h3>小明今天吃了几个鸡腿 ?</h3>
        <p>答:{`吃了${this.state.number}个`}<Son sendData={this.getData.bind(this)}/></p>
      </div>
    )
  }
}

class Son extends Component {
  constructor(props) {
    super(props)
    this.state = {
      number: 10,
      text: '(点我告诉你答案)'
    }
  }

  handleClick(){
    this.props.sendData(this.state.number)
    this.setState({
      text: ''
    })
  }

  render() {
    return (
      <i style={{color: 'blue', cursor: 'pointer'}} onClick={this.handleClick.bind(this)}>
        {this.state.text}
      </i>
    )
  }
}
React组件通信可以通过props属性进行传递数据。子组件可以通过props接收父组件传递的数据,并进行相应的操作。在函数式组件中,可以直接通过props对象来获取父组件传递的数据。在类组件中,需要使用this.props来获取父组件传递的数据。\[1\] 另外,子组件也可以通过调用父组件传递过来的函数来实现子传父的通信。子组件可以将需要传递的数据作为函数的实参传入,并在子组件内部调用该函数。这样就可以将子组件的数据传递给父组件进行处理。\[3\] 总结起来,React组件通信可以通过props属性进行父传子和子传父的数据传递和操作。父组件通过props将数据传递给子组件,子组件通过props接收父组件传递的数据。子组件可以通过调用父组件传递的函数来将子组件的数据传递给父组件进行处理。\[1\]\[3\] #### 引用[.reference_title] - *1* *3* [React组件通信](https://blog.csdn.net/weixin_52148548/article/details/125287315)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [react组件通信](https://blog.csdn.net/weixin_39818813/article/details/125737028)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值