Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

javascript - Ref callback attribute is not working as expected

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.

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

What is the reason for this?

Start typing inside the input box

Example 1(this works fine)

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Adding to Fabian Schultz

This happens because in the first case, you're passing a reference of the function to the ref. During the initial render, the referenced function will be instantiate (a instance is created) and the element will be passed to that function. For the following renders(re-renders), this instance remains the same. So, React won't call this function as it is already being called.

But, in the second case, a arrow function is passed in as a value. So, for every re-renders the function will be passed again as the value. This results in two instances of arrow functions. One, from the previous render and the second from the recent render. Due to this, React nullifies the previous instance of the function. So, it returns null for the previous instance of the function and returns the element to the recent instance of the function.

Point to take: Always use function reference for ref

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...