React支持一种非常特殊的属性Ref,你可以用来绑定到 render输出的任何组件上。
用法:在组件中设置属性ref="xxx",则通过this.refs.xxx对该组件进行直接引用。
var RefTest = React.createClass({
handleClick:function(){
this.refs.myInput.focus(); //获取焦点
console.log(ReactDOM.findDOMNode(this.refs.myInput)); //打印 <input type="text">
},
render:function(){
return (
<div>
<input type="text" ref="myInput" />
<input type="button" value="click_get_focus" onClick={this.handleClick} />
</div>
);
}
});
ReactDOM.render(<RefTest />,document.getElementById("example"));
(小贴士)你可能首先会想到在你的应用程序中使用 refs 来更新组件状态。如果是这种情况,提升 state 所在的组件层级会是更合适的做法,即状态提升。
新的创建API:React.createRef()
React v16.3 引入的 React.createRef()
API 更新,使用 React.createRef()
创建 refs。
import React from 'react';
class CustomTextInput extends React.Component {
//构造函数
constructor(props) {
super(props);
this.textInput = React.createRef(); // 创建ref, 存储 textInput DOM 元素
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
this.textInput.current.focus(); // 通过 "current" 取得 DOM 节点,直接使用原生 API 使 text 输入框获得焦点
console.log(this.textInput);
}
render() {
// ref={this.textInput}代码,是想告诉React我们想把<input> ref关联到构造器里创建的`textInput` 上
return(
<div>
<input defaultValue="hello ref" type="text" ref={this.textInput} />
<input type="button" value="Focus the text input" onClick={this.focusTextInput} />
</div>
);
}
}
//导出组件
export default CustomTextInput;
在构造函数中,refs 通常被赋值给组件实例的一个属性this.xxx,这样你可以在组件中任意一处使用它们。当this.xxx被传递给一个 render
函数中的元素时,可以使用 this.xxx.current 属性对节点的引用进行访问。其中current的值的类型取决于节点的类型:
1.当 ref 属性被用于一个普通的 HTML 元素时,React.createRef() 将接收底层 DOM 元素作为它的 current 属性以创建 ref 。
2.当 ref 属性被用于一个自定义类组件时,ref 对象将接收该组件已挂载的实例作为它的 current 。
3.你不能在函数式组件上使用 ref 属性,因为它们没有实例。
父级组件对CustomTextInput里的内部方法引用:
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();
}
render() {
return (
<CustomTextInput ref={this.textInput} />
);
}
}
创建的另一种方法:回调 ref
这种方法更加细致地控制何时 ref 被设置和解除。
官网例子:
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => {
this.textInput = element;
};
this.focusTextInput = () => {
// 直接使用原生 API 使 text 输入框获得焦点
if (this.textInput) this.textInput.focus();
};
}
componentDidMount() {
// 渲染后文本框自动获得焦点
this.focusTextInput();
}
render() {
// 使用 `ref` 的回调将 text 输入框的 DOM 节点存储到 React
// 实例上(比如 this.textInput)
return (
<div>
<input type="text" ref={this.setTextInputRef} />
<input type="button" value="Focus the text input" onClick={this.focusTextInput} />
</div>
);
}
}
或通过父级传入element,实现父级控制子级DOM节点的目的:
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return (
<CustomTextInput inputRef={el => this.inputElement = el} />
);
}
}
(小贴士)比较React.createRef()
和回调 ref,两种方式只是写法上的差异,差异点如下:
// React.createRef()方式
var createReactClass = require('create-react-class');
var App = createReactClass({
componentWillMount: function() {
this.textInput = React.createRef(); // 差异1:定义
},
componentDidMount: function() {
this.textInput.current.focusTextInput(); // 差异2:使用
},
getInitialState: function() {
return {}
},
render: function() {
return(
<div>
<CustomTextInput ref={this.textInput} /> // 差异3:赋值
</div>
);
}
});
ReactDOM.render(<App />, document.getElementById("content"));
// ref回调方式
var createReactClass = require('create-react-class');
var App = createReactClass({
componentWillMount: function() {
this.ele = null; // 差异1:定义
},
componentDidMount: function() {
this.ele.focusTextInput(); // 差异2:使用,此处无需current
},
getInitialState: function() {
return {}
},
render: function() {
return(
<div>
<CustomTextInput ref={(element)=>this.ele = element}/> // 差异3:赋值
</div>
);
}
});
ReactDOM.render(<App />, document.getElementById("content"));
不能再函数组件上使用ref属性
由于函数组件没有实例,故以下用法是错误的:
function MyFunctionComponent() {
return <input />;
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
// This will *not* work!
return (
<MyFunctionComponent ref={this.textInput} />
);
}
}
如果你需要使用 ref,你应该将组件转化为一个 class,就像当你需要使用生命周期钩子或 state 时一样。