简要介绍:React16.3中修改了Refs的使用方法,并且提供了Forwarding Refs用于在父组件中操作子组件中的dom节点,本文介绍一下新的Refs表示方法以及Forwarding Refs。
Ref的功能就不具体说了,就是在父组件中直接操作子组件的方法,Ref的方式,使其脱离了props传值,然后更新子组件的标准方法。
1 . React16.3中的Refs
(1)创建
16.3版本中Refs通过React.createRef()的方法创建,通过ref属性关联,比如我们创建一个Child子组件,并在该组件中使用Ref:
class Child extends React.Component{
constructor(props){
super(props);
this.myRef=React.createRef();
//React16.3中创建Ref的方法
}
render(){
return <input ref={
this.myRef}/>
}
}
上述是创建Ref指向的方法,在Ref所指向的组件,在render后就可以调用,React16.3中提供了current属性,用于引用render后的节点:
componentDidMount(){
console.log(this.myRef.current);
//render之后就可以输出该ref指向的那个节点
}
此外,同样的Ref所指向的节点可以是dom节点,也可以是类组件。
(2)Ref属性指向的节点不能是函数组件
因为我们通过ref获得的组件,包含了声明周期和state,因此ref所指向的组件不可以是函数组件。
function MyFunctionComponent(){
return <div>1</div>
}
class Child extends React.Component{
constructor(props){
super(props);
this.myRef=React.createRef();
}
render(){