简体   繁体   中英

React createRef() vs callback refs. Is there any advantage of using one over the other?

I have started working on React recently and understood how refs can be used to get hold of a DOM node. In the React docs, they mention the two approaches of creating Refs. Can you please let me know in what situation a callback ref is better than createRef()? I find createRef to be simpler. Although the docs say "callback refs give you more fine grain control" I can't understand in what way. Thank you

Besides what jmargolisvt said, one thing I found callback is very interesting that I can set multiple refs in an array so that I can control it better. Like this:

class A extends React.Component {
    constructor(props) {
        super(props);
        this.inputs = [];
    }

    render() {
        return [0, 1, 2, 3].map((key, index) => (
            <Input 
                key={key} 
                ref={input => this.inputs[index] = input}
            />)
        );
    }
}

createRef is returning either a DOM node or a mounted instance of a component, depending on where you call it. Either way, what you have in hand is indeed straightforward as you've noted. But what if you want to do something with that reference? What if you want to do it when the component mounts ?

Ref callbacks are great for that because they are invoked before componentDidMount and componentDidUpdate . This is how you get more fine-grained control over the ref. You are now not just grabbing DOM elements imperatively, but instead dynamically updating the DOM in the React lifecycle, but with fine-grained access to your DOM via the ref API.

In terms of use cases, callback refs can do anything createRef can do, but not vice versa. createRef gives us a simplified syntax, but that's it.

Things you can't do with createRef :

  • React to a ref being set or cleared
  • Use an externally and internally provided ref on the same React element at the same time. (eg you need to measure a DOM element's clientHeight whilst, at the same time, allowing an externally provided ref (via forwardRef ) to be attached to it.)

实际上,除了callback ref 在初始渲染之前返回 null 之外,您不会看到任何区别。

This answer is a little biased on React-Native but still it is applicable if a React component similar to the following example.

<Animated.View> is a wrapper component for <View> that can be animated.

However if you want to access the <View> directly for something like calling the measure() method, then you can do it like:

interface State {
  ref: View;
}

public render() {
  <Animated.View ref={(component) => {
      if (component !== null) {
        this.state.ref = component.getNode();
      }
    }}
  >
    ...
  </Animated.View>
}

Otherwise, you need to do: this.state.ref.getNode() .

TL;DR: you have control of what to do with an element or how to store it.

If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn't matter in most cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM