小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。
refs 概念
refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。
String 类型的 refs
使用 refs 最简单的方法是直接使用 String 类型的 refs:<input ref="input1"/>
、this.refs.input1
。
从官网上可以看到这种 String 类型的 refs 已经过时不建议使用。
回调函数形式的 refs
React 将在组件挂载时,会调用
ref
回调函数并传入 DOM 元素,当卸载时调用它并传入null
。在componentDidMount
或componentDidUpdate
触发前,React 会保证 refs 一定是最新的。
class Demo extends React.Component {
showInfo = () => {
const { input } = this;
console.log(input.value);
}
saveInput = (c) => {
this.input = c;
console.log('@', c);
}
render() {
return(
<input ref={this.saveInput} type="text" /><br/><br/>
<button onClick={this.showInfo}>点我提示输入内容</button>
)
}
}
复制代码
官网上说明了有一个需要注意的问题:ref 回调函数在以内联函数的形式定义的时候,在更新过程会被执行两次,一次传入参数 null
(清空旧的 ref),一次传入参数 DOM
元素(设置新的 ref)。如果使用绑定函数的形式那么在更新的时候只会执行一次并传参 DOM
元素。
实际开发中内联函数的 ref 回调函数会用的更多,因为更加方便,虽然在更新过程会被执行两次,但是大部分情况下不会有太大影响。
createRef 的使用
React.createRef
调用后可以返回一个容器,该容器可以存储被 ref 所标识的节点,并且该容器只能存储一个节点,即“专人专用”。
class MyComponent extends React.Component {
myRef1 = React.createRef();
myRef2 = React.createRef();
showData1 = () => {
// 使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。
alert(this.myRef1.current.value);
}
showData2 = () => {
alert(this.myRef2.current.value);
}
render() {
return(
<input ref={this.myRef1} type="text" /><br/><br/>
<button onClick={this.showData1}>点我提示输入内容</button>
<input onBlur={this.showData2} ref={this.myRef2} type="text" /><br/><br/>
);
}
}
复制代码