将子节点的ref暴露给父节点
- 16.3以上 Refs转发,将ref自动通过组件传递给子组件
1. 在父组件创建ref对象
2. 给子组件赋值ref
3. 通过React.forward向子组件转发ref属性
4. 父组件的ref对象指向子组件dom
5. ref参数只有在 React.forwardRef 组件内定义时可接受
const MyInput = React.forwardRef((props, ref) =>
<input type="text" placeholder={
props.placeholder} ref={
ref} />
)
class App extends React.Component {
constructor(props) {
super(props)
this.refInApp = React.createRef()
}
componentDidMount() {
console.log('【APP】componentDidMount', this.refInApp)
}
inputOperate = () => {
const oInput = this.refInApp.current
oInput.focus()
}
render() {
return (
<>
<MyInput ref={
this.refInApp} placeholder="请输入" />
<button onClick={
this.inputOperate}>聚焦</button>
</>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
)

在高阶组件中转发
- 匿名改具名

class MyInput extends React.Component {