引用回调属性未按预期工作 [英] Ref callback attribute is not working as expected

查看:34
本文介绍了引用回调属性未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个使用 ref回调属性的例子。第一个on有一个对回调函数的引用。第二个箭头函数声明为值。

I've two examples using the ref callback attribute. The first on has a reference to the callback function. The second one has an arrow function declared as the value.

第一个按预期工作。但是,第二个在连续渲染时记录 null

The first works as expected. But, the second one log a null on consecutive renders.

这是什么原因?

开始在输入框内输入

示例1(此工作正常)

class App extends React.Component{
  constructor(props){
    super(props)
    this.refCallback = this.refCallback.bind(this)
    this.state = {}
  }
  
  refCallback(el){
    console.log(el)
  }
  
  render(){
    return <input type="text"
      value={this.state.value}
      ref={this.refCallback}
      onChange={(e) => this.setState({value: e.target.value})}
      />
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

示例2(这是不工作)

class App extends React.Component{
  constructor(props){
    super(props)
    this.state = {}
  }

  render(){
    return <input type="text"
      value={this.state.value}
      ref={(el) => console.log(el)}
      onChange={(e) => this.setState({value: e.target.value})}
      />
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

推荐答案

这已经简要讨论了React的Github问题。我会试着解释一下,但是用文字来说很难。

This has been discussed briefly on React's Github issues. I'll try to explain this, but it's kind of hard to put in words.

因为你在第二个例子中没有调用智能组件方法,每次重新呈现组件时都会发生 console.log(el),这意味着当特定节点(在本例中为输入)被删除并呈现时它也会调用再次,无论 el 是否实际发生了变化。当它被React删除时,它返回 null ,因为该元素不再存在,即使它只是一小段时间。似乎这样做是为了完成。

Since you're not calling a "smart" component method in your second example, the console.log(el) happens every time the component is re-rendered, which means it also calls when the specific node (in this case your input) is removed and rendered again, regardless if the el actually changed. When it is being removed by React it returns null because the element doesn't exist anymore, even if it's just for a fraction of a second. Seems like this is done for the sake of completion.

这是鸣叫解释了这一点。

这篇关于引用回调属性未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆