美文网首页
React refs和onRefs的使用

React refs和onRefs的使用

作者: 子涵_520 | 来源:发表于2020-05-19 18:58 被阅读0次

父组件代码块

constructor(props){
    super(props);
    this.refBox = React.createRef()
    this.state={
      message:"i am from parent"
      content:"1111"
    }
  }
handleChange = ()=>{
  this.setState({
      message:"changed by parent"
  })
}
  render(){
  const = { message,content } = this.state;
  //parentMethods 中可以放变量,方法,对应的到子组件中可以直接使用
  const parentMethods = {
    msg:message,
    handleChange:this.handleChange
   }
    return(
          <Child {...parentMethods}  ref={this.refBox}/>
    )
  }
}

子组件代码块

@Form.create()
export default class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     childMsg:"I am from child"
    };
  }
 
  render() {
  //msg,handleChange两个参数就是从父组件中获取的
  const { msg,handleChange,form:{getFieldDecorator}} = this.props
    return (
      <div>
        <div onClick={()=>handleChange()}>{msg}</div>//显示的内容就是 "i am from parent"
         <Form>
          <Form.Item>
           {getFieldDecorator("name",{
               initialValue:null
             })(
               <Input />
             )}
          </Form.Item>
        </Form>
      </div>
    );
  }
}
父组件向子组件传值主要依靠父组件中parentMethods将方法和变量传递到子组件中
父组件获取子组件的form表单数据并且可以操作

方式一:在父组件使用子组件的地方添加ref={this.refBox}然后在constructor中添加声明

image.png
然后就可以在父组件中拿到子组件关于form表单的变量内容
this.refBox.current,如果不清楚的话,可以在使用之前先console.log(this.refBox.current),就可以看到里面的具体内容如下图所示:
image.png

方式二:

<Child ref={(ref)=>this.refBox=ref } />

方式三:

<Child ref={this.refBox } />

三种方式写法不一样,使用都是一样的通过this.×××.current改变子组件中的form表单

父子组件间的通信:

<Child onRef={(ref)=>{this.child = ref;}} />

子组件获取父组件中得方法或者变量,还是按照最上面第一张图中得注释,定义一个parentMethods来传递
父组件获取子组件state定义的变量
this.child.state.childMsg ,console.log(this.child)如下图所示:

image.png

我一般会把方式二和父子组件得通信混淆,写法上一个是ref一个是onRef,大家可以自己尝试一下,写这篇文章也是为了让自己对react有更深入的了解,谢谢。

相关文章

网友评论

      本文标题:React refs和onRefs的使用

      本文链接:https://www.haomeiwen.com/subject/ywvpnhtx.html