React特性之 refs
1. 概念
Refs: 在计算机中成为弹性文件系统(Resilient File System,简称ReFS)
React中的Refs提供了一种方法,允许我们访问DOM节点或在render方法中创建的React元素,本质为ReactDOM.render( )返回的组件实例,如果渲染组件则返回的是组件实例,如果渲染dom则返回的是具体的dom节点。
2. 应用
方式一: createRef (版本>= React16.3)
一般在构造函数中将refs分配给实例属性,以供组件的其它方法中使用
1.对于html元素:可以获取元素示例
<div id="root"></div>
<script type="text/babel">
class DEMO extends React.Component{
constructor(props) {
super(props);
this.myRef = React.createRef(); // 调用后可以返回一个容器,该容器可以存储被ref所标识的节点,该容器是“专人专用”的
console.log(this.myRef); //当前current属性 内被ref所标识的节点<div>
}
componentDidMount(){
this.myRef.current.innerHTML = '哈利路亚' //this.myRef中有一个current属性
}
render() {
return (
<div>
<div ref={this.myRef} /> {/*如果ref属性被用于html元素,那么它的值就是底层DOM元素*/}
</div>
)
}
}
ReactDOM.render(<DEMO />,document.getElementById('root'))
</script>
被ref所标识的节点
2.对于类组件:获得组件类的实例
<div id="root"></div>
<script type="text/babel">
class Parent extends React.Component {
constructor(props){
super(props)
this.myRef = React.createRef();
console.log(this.myRef);
}
componentDidMount() {
this.myRef.current.bianshen(); //在父组件中调用了子组件的方法
}
render(){
return (
<Children ref={this.myRef}/>
)
}
}
class Children extends React.Component {
bianshen(){
console.log('吉普赛人大变身!');
}
render(){
return(
<span>吉普赛人大变身!</span>
)
}
}
ReactDOM.render(<Parent/>,document.getElementById('root'))
提示:对于Function Components:无法获取
方式二: 回调Refs
React 将在组件挂载时,会调用 ref 回调函数并传入 DOM 元素,当卸载时调用它并传入 null。在 componentDidMount 或 componentDidUpdate 触发前,React 会保证 refs 一定是最新的。
eg1:
<div id="root"></div>
<script type="text/babel">
class Example extends React.Component{
constructor(props){
super(props);
this.targetRef = null;
this.myRef = (currentNode)=> this.targetRef = currentNode;
}
componentDidMount() {
if(this.targetRef) {
this.targetRef.innerHTML = '哈利路亚';
}
}
render() {
return(
<div ref={this.myRef} />
)
}
}
eg2:
class Demo extends React.Component{
// 展示左侧输入框的数据
showData = ()=>{
// 从实例自身取
const {input1} = this;
alert(input1.value)
}
render(){
return(
<div>
{/*回调函数:内联函数 把ref当前所处的节点挂载在了实例自身上并且取了名字叫input1*/}
<input ref={(currentNode)=>{this.input1 = currentNode}} type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData}>点击我提示数据</button>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('root'))
</script>
方式三:String 类型的 Refs (已过时,不推荐使用)
class StringRef extends React.Component {
componentDidMount() {
console.log('this.refs:' +this.refs.container)
}
render() {
return(
<div ref='container'>德云社</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('root'))
3. React中的refs作用是什么?
Refs 是 React 提供给我们的安全访问 DOM 元素或者某个组件实例的句柄。在类组件中,React将ref属性中第一个参数作为DOM中的句柄。而函数组件中,react用hooks的api useRef也能获得ref。