react 字父组件传值

父组件相关代码:

import React, { Component } from 'react'; // 引入相关模块
import Child from '@/Child'; 
export default class extends Component {
  constructor (props) {
    super(props);
    this.state = {

    }
  }

  getData (str) {
    console.log(str)
  }  // 接受子组件传递过来的数据
  render () {
    return (
      <div> 
        {/* 在父组件调用子组件的地方,给子组件类似于添加一个属性为函数,一定要注意this的指向问题 */}
        <Child fn={ this.getData.bind(this)}/>
      </div>
    )
  }
}

子组件相关代码:

import React, { Component } from 'react'

class Com extends Component {
 
  render () 
    // return (
    //   <button onClick={ this.sendData.bind(this) }>给父组件传值</button>
    // )
    {
      return (
        // console.log(this.props) fn
        // 子组件可以通过父组件传递过来的函数fn()的执行来传递参数
      <button onClick={ ()=>this.props.fn('11111')}></button>
      )
    }
  }
 

export default Com;

以上我们家完成了react的子组件向父组件传值

猜你喜欢

转载自www.cnblogs.com/huangping199541/p/11853858.html