场景:一个输入框组件,我要在父组件触发一个事件,来触发输入框组件的focus聚焦
父组件
handleClick = () => {
this.SubInput.handleFocus()
}
render() {
return (
<div>
<SubItem ref={ref => this.SubInput = ref}>
</SubItem>
<button onClick={this.handleClick}>点击</button>
</div>
);
}
}
输入框组件
...
handleFocus = () => {
this.Input.focus()
}
render() {
return (
<input type="text" ref={ref => this.Input = ref}/>
);
...
输出父组件获取到的ref ,可以发现,不仅是在子组件内(this)的所有属性和方法都暴露出来了
这样就可以通过ref的方式,让父组件来触发子组件的事件了
16.3版本后,通过React.createRef的方式来获取ref,不过需要使用current来获取整个子组件的属性和方法
let SubInput = React.createRef()
class Sub extends Component {
handleClick = () => {
console.log(SubInput)
}
render() {
return (
<div>
<SubItem ref={SubInput.current}>
</SubItem>
<button onClick={this.handleClick}>点击</button>
</div>
);
}
}
export default Sub
let InputRef = React.createRef()
export default class SubItem extends Component {
handleFocus = () => {
this.Input.focus()
}
render() {
return (
<input type="text" ref={InputRef}/>
);
}
}
也可以写在constructor里
constructor(props) {
super(props)
this.SubInput = React.createRef()
}
获取的内容都一样: