0
点赞
收藏
分享

微信扫一扫

react回调refs更新过程中执行两次


如果 ref 回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次,第一次传入参数 ​​null​​​,然后第二次会传入参数 DOM 元素。这是因为在每次渲染时会创建一个新的函数实例,所以 React 清空旧的 ​​ref​​​ 并且设置新的。通过将 ​​ref​​​ 的回调函数定义成 ​​class​​ 的绑定函数的方式可以避免上述问题,但是大多数情况下它是无关紧要的。

内联函数的方式定义

class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'hello'
}
this.textInput = null
}

handleChange = (e) => {
this.setState({
name: e.target.value
})
}

handleClick = () => {
this.setState({
name: 'world'
})
}

render() {
return (
<div>
<input
type="text"
value={this.state.name}
onChange={this.handleChange}
ref={(element) => {console.log(element);this.textInput = element}}
/>
<button onClick={this.handleClick}>change</button>
</div>
);
}
}

输出结果

​null​​​​<input type="text" value="world">​

class 绑定函数的方式

class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'hello'
}
this.textInput = null
this.setTextInputRef = element => {
console.log(element)
this.textInput = element
}
}

handleChange = (e) => {
this.setState({
name: e.target.value
})
}

handleClick = () => {
this.setState({
name: 'world1'
})
}

render() {
return (
<div>
<input
type="text"
value={this.state.name}
onChange={this.handleChange}
ref={this.setTextInputRef}
/>
<button onClick={this.handleClick}>change</button>
</div>
);
}
}


举报

相关推荐

0 条评论