react forwardRef 意义

IT技术 javascript node.js reactjs ecmascript-6
2021-04-27 18:28:16

我不明白这有什么意义:

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

如果我能做到这一点:

function FancyButton(props) {
  return (
    <button className="FancyButton" ref={props.ref}>
      {props.children}
    </button>
  );
}
1个回答

从文件

Ref forwarding 是一种通过组件自动将 ref 传递给其子组件的技术。

Ref forwarding 是一个选择加入的功能,它让一些组件接受他们收到的 ref,并将它进一步向下传递(换句话说,“转发”它)给子组件。

对于你的问题

我不明白这有什么意义:如果我能做到这一点:。

您可以选择第一种方法或第二种方法

例子

// EmailInput wraps an HTML `input` and adds some app-specific styling.
const EmailInput = React.forwardRef((props, ref) => (
  <input ref={ref} {...props} type="email" className="AppEmailInput" />
));

class App extends Component {
  emailRef = React.createRef();

  render() {
    return (
      <div>
        <EmailInput ref={this.emailRef} />
        <button onClick={() => this.onClickButton()}>
          Click me to focus email
        </button>
      </div>
    );
  }

  // `this.emailRef.current` points to the `input` component inside of EmailInput,
  // because EmailInput is forwarding its ref via the `React.forwardRef` callback.
  onClickButton() {
    this.emailRef.current.focus();
  }
}

对我来说,fowardRef 不需要太多,因为我们总是可以使用另一种方法传递 ref

你可以在这里阅读更多