Refs and the DOM
提供了一个指向Dom
的引用,可以访问Dom
节点或者已经创建的React
组件.
使用时机
焦点处理、文本选择、媒体文件的回放
触发一个动画命令
集成第三方的
Dom
库时不要过度使用
Refs
创建Refs
通过React.createRef()
方法来创建,示例:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <input ref={this.myRef} />;
}
}
Refs使用
通过const input = this.myRef
就可以获取到input
这个Dom
了.
组件加载完获取焦点的示例:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
componentDidMount() {
if(this.myRef) {
this.myRef.current.focus();
}
}
render() {
return (
<div>
<input defaultValue="no focus"/>
<p/>
<input ref={this.myRef} defaultValue="has focus"/>
</div>
)
}
}
通过回调的方法创建
子组件:
const CustomTextInput = ({inputRef}) => {
return <input ref={inputRef}/>
}
父组件:
class Parent extends React.Component {
componentDidMount() {
if(this.inputElement) {
this.inputElement.focus();
}
}
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}