下面是几个适合使用 refs 的情况:
管理焦点,文本选择或媒体播放。---操作DOM
触发强制动画。
集成第三方 DOM 库。
1. this.refs 字符串—已废弃—依然可以用
2. React.createRef() 推荐使用-React16.3
import React, { Component } from 'react'
export default class App extends Component {
constructor(){
super();
this.myInput=React.createRef();
}
handdleClick=()=>{
console.dir(this.myInput.current);
this.myInput.current.focus();
}
render() {
return (
<div>
<input type="text" ref={this.myInput} />
点击让文本框获得焦点
</div>
)
}
}
3. 回调函数 ref={回调函数}
import React from 'react'
//孙子
function GrandCihld(props) {
return (
<div>
);
}
//儿子
function Child(props) {
return (
<div> My input: <GrandCihld inputRef={props.inputRef} /></div>
);
}
//父亲
class App extends React.Component {
handdleClick=()=>{
console.log("this.inputElement",this.inputElement);
this.inputElement.focus();
}
render() {
return (
<div>
<Child inputRef={el => {
this.inputElement = el;
console.log("匿名函数被调用了");
}} />
点击获取焦点
</div>
);
}
}
export default App;