V16之前
class Parent extends Component {
constructor(props, context) {
super(props, context);
this.r = null
}
componentDidMount() {
this.r.onClick()
}
render() {
return (
<div>
<Child ref={r => this.r = r} />
</div>
)
}
}
但是这个方式有个问题,组件渲染时,行内函数会执行两次,第一次为初始值,第二次才是真正的DOM
V16之后
新增了createRef API
1、使用React.createRef()
创建Ref
class Child extends React.Component{
constructor(props){
super(props);
this.myRef=React.createRef();
//React16.3中创建Ref的方法
}
render(){
return <input ref={this.myRef}/>
}
}
2、为了能让子组件中的元素接收来自父组件的ref,就要让子组件接收 ref
并且通过React.forwardRef
转发给元素
import React, {Component} from 'react';
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref}>{props.children}</button>
))
class Parent extends Component {
constructor(props, context) {
super(props, context);
this.r = React.createRef()
}
render() {
return (
<FancyButton ref={this.r}>Click me!</FancyButton>
);
}
}
这样父组件的ref this.r
就能传递给子组件中的ref了
3、使用父组件的current
属性,获取当前元素
this.r.curent
在高阶组件转发refs
待定