ref在react里面总共有3种写法:字符串形式,回调函数形式,createRef。
1.字符串形式(该形式已经被react官方抛弃,官方说将来可能会弃用。但是现在依旧可以使用,不过不推荐)
class Demo extends React.Component {
render() {
return (
<div>
<button ref='btn' onClick={this.showDate}>打印节点</button>
</div>
);
}
showDate = () => {
console.log(this.refs.btn)
}
}

2.1.内联回调函数写法
class Demo extends React.Component {
render() {
return (
<div>
<button ref={(c) => {console.log(c); this.btn = c}} onClick={this.showDate}>打印节点</button>
</div>
);
}
showDate = () => {
console.log(this.btn)
}
}

ref的回调函数完整写法为(currentNode)=> { this.inp1 = currentNode }
,该回调函数的参数表示当前节点,也就是我们需要操作的元素节点。回调函数里面的this指的是当前类的实例。将此节点绑定到实例的属性上,需要用时直接使用this.属性就可直接调用。(ref的回调函数为react自动调用。)
class Demo extends React.Component {
state = {num: 0}
render() {
return (
<div>
<button ref={(c) => {console.log(c); this.btn = c}} onClick={this.showDate}>打印节点</button>
</div>
);
}
showDate = () => {
this.setState({num: this.state.num + 1})
}
}

注意:如果 ref 回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次,第一次传入参数 null,然后第二次会传入参数 DOM 元素。
通过将 ref 的回调函数定义成 class 的绑定函数的方式可以避免上述问题,但是大多数情况下它是无关紧要的。
2.2. 非内联回调函数
class Demo extends React.Component {
state = {num: 1}
render() {
return (
<div>
<button ref={this.REF_inp} onClick={this.showDate}>打印节点</button>
</div>
);
}
showDate = () => {
this.setState({num: this.state.num + 1})
}
REF_inp = (c) => {
this.inp1 = c;
console.log(c)
}
}
只会打印一次节点,不会随render函数更新

3.React.createRef()
class Demo extends React.Component {
Ref_box = React.createRef()
render() {
return (
<div>
<button ref={this.Ref_box} onClick={this.showDate}>打印节点</button>
</div>
);
}
showDate = () => {
console.log(this.Ref_box.current)
}
}

React.createRef()会返回一个容器,该容器可以存储被ref所标识的节点。但是该容器是“专人专用”,只会存储一个节点。若只有一个容器而有多个ref绑定的节点,后一个会覆盖前一个节点。所以想要存储多个节点,只能创建多个React.createRef()容器。
网友评论