什么时候使用
当需要访问当前的DOM节点或者当前的react组件的时候可以使用(例如文本框获取焦点等),但是不要过度使用该属性
使用Refs方法
使用React.createRef()创建这个属性,使用current来得到当前的DOM节点或者React组件
例如: 将ref添加到DOM节点上
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();//在这里创建
}
focusTextInput=()=>{
this.textInput.current.focus();//当点击这个函数的时候使用current来获取当前的DOM节点
}
render() {
return <input ref={this.myRef} type="text"/>;//使用的时候将创建的ref赋值给ref属性就可以了 之后获取到的就是这个节点
<input type="button" value="Focus the text input" onClick={this.focusTextInput}/>//绑定点击函数
}
}
例如:将ref添加到React组件上
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();//当组件加载的时候获取CustomTextInput组件并调用其内部的聚焦函数
}
render() {
return (
<CustomTextInput ref={this.textInput} />//使用上面定义好的组件
);
}
}
注意:不要将ref用在使用 function定义的组件,因为他没有实例,因此如果需要使用ref的话请使用定义类的方式来定义组件
但是我们可以在其内部使用ref。
例如:这样是不行的
function MyFunctionalComponent() {
return <input />;
}
<MyFunctionalComponent ref={this.textInput} />//这里是不行的
解决方案: 使用 React.forwordRef 这个api来包装, 父组件可以像子组件传递 ref
const MyFunctionalComponent = React.forwardRef((props, ref) => {
return <input ref/>;
})
<MyFunctionalComponent ref={this.textInput} />
将DOM的ref暴露给父亲组件
即将创建的refs通过Props来传递给子组件,在子组件中使用该refs 这样就达到了在父亲组件中引用子组件的效果) 这种模式甚至可以在几层组件当中工作 如爷爷组件可以控制孙子组件
例子:
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />//在子组件中使用props来获取在父亲组件创建的refs
</div>
);
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.inputElement = React.createRef();//创建Refs
}
render() {
return (
<CustomTextInput inputRef={this.inputElement} />//通过道具将Refs传递过去
);
}
}
使用Callback Refs
即在给ref传递值的时候不传递一个具体的创建好的refs而是传递一个方法,该方法接受一个React组件的实例或者一个HTMLDOM
例如:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => {
this.textInput = element;//该方法在这里将组件或者HTMLDOM绑定到this.textInput
};
this.focusTextInput = () => {
if (this.textInput) this.textInput.focus();//这里的this.textInput已经绑定到<input/> 于是可以使用
};
}
componentDidMount() {
this.focusTextInput();
}
render() {
return (
<div>
<input
type="text"
ref={this.setTextInputRef}//在这里传递过去的是一个回掉函数
/>
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}