Refs的转发机制
默认的是拿到是组件的实例,而不能获取子组件的节点
import React, { Component, createRef } from 'react'
class MyInput extends Component {
render() {
return (
<input type="text" placeholder="请填写.." />
)
}
}
export default class App extends Component {
constructor(props) {
super(props)
this.myInputRef = createRef()
}
componentDidMount() {
console.log(this.myInputRef)
}
render() {
return (
<div>
<MyInput ref={ this.myInputRef }></MyInput>
</div>
)
}
}
把子组件的节点的 ref暴露给父组件(16.3以上,refs转发)
- forwardRef: 方法实现这个需求
import React, { Component, createRef, forwardRef} from 'react'
//=> 3.通过forwardRef向input转发ref
const MyInput = forwardRef((props, ref) => {
return (
// => 5. ref参数只能用于 forwardRef定义的组件可使用
<input type="text" placeholder={ props.placeholder } ref={ ref }/>
)
})
export default class App extends Component {
constructor(props) {
super(props)
//=> 1.创建ref对象
this.myInputRef = createRef()
}
componentDidMount() {
//=> 4.this.myInputRef.current ->(指向) input
console.log(this.myInputRef)
}
inputOpreate() {
const oInput = this.myInputRef.current;
//清空input
oInput.value = '';
// 聚焦
oInput.focus();
}
render() {
return (
<div>
{/* 2.给组件赋值ref */}
<MyInput ref={ this.myInputRef } placeholder="请填写..."></MyInput>
<button onClick={this.inputOpreate.bind(this)}>Click</button>
</div>
)
}
}
Ref在高阶组件的使用
import React, { Component, createRef, forwardRef} from 'react'
class MyInput extends Component {
render() {
return (
<input type="text" placeholder={ this.props.placeholder } />
)
}
}
function InputHoc(WrapperComponent) {
class Input extends Component {
render() {
//=> 获取 ref 和 props
const { forwardedRef, ...props } = this.props
return <WrapperComponent ref={ forwardedRef } {...props}/>
}
}
return forwardRef((props, ref) => {
return <Input { ...props } forwardedRef={ ref }/>
})
}
const MyInputHoc = InputHoc(MyInput)
export default class App extends Component {
constructor(props) {
super(props)
this.myInputRef = createRef()
}
componentDidMount() {
console.log(this.myInputRef, 'componentDidMount')
}
render() {
return (
<div>
<MyInputHoc ref={ this.myInputRef } placeholder="请填写..."/>
</div>
)
}
}