React父子组件间的通信是怎样进行的?

父子组件通信方式

(1)传递数据(父传子)与传递方法(子传父)

(2)ref标记(父组件拿到子组件的引用,从而调用子组件的方法)

父传子

使用 props属性,传入props

this.props.数据

//父组件
 <Field label="用户名"></Field>
//子组件
 <label>{this.props.label}</label>

子传父

父组件向子组件传一个函数,然后通过子组件中这个函数的回调,拿到子组件穿过的值

this.props.函数名()

//子组件
<input onChange={(evt)=>{
   this.props.onChangeEvent(evt.target.value)
}}></input>
//父组件
 <Field onChangeEvent={(value)=>{
    console.log(value)
 }}></Field>

ref标记(传递数据)

在组件身上绑定ref,直接通过 this.username.current 获得整个组件,this.username.current.state获得子组件内state数据

this.ref名.current

//子组件中
 state={
     value:''
 }
 <input onChange={(evt)=>{
   this.setState({
       value:evt.target.value
   })
}}></input>
//父组件
username = React.createRef()
<Field ref={this.username}></Filed>
....
console.log(this.username.current.state.value)