React forwardRef 的含义

8

我不明白这是什么意思:

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>
  );
}

你应该在父组件中使用 createRef 并通过 forwardRef 将其链接到子组件。 - Alexey Nikonov
1个回答

4

从这些文件中

引用转发是一种通过组件自动传递 ref 给其子组件的技术。

引用转发是一项可选特性,它允许某些组件接收 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();
  }
}

对我来说,forwardRef并不是必需的,因为我们总可以使用另一种方法传递ref。

你可以在这里阅读更多信息。


3
据我看来,需要使用forwardRef是因为在React组件上没有this.props.ref属性,而只有在某些低级别元素上才有,而且函数式组件上也没有。但是我之前一直以为它可以工作。 - luky
2
@TonyNgo,那篇文章非常有启发性,正是我在寻找的。有趣的是,官方文档没有提到将引用作为普通属性传递,但实际上这似乎是一个可以接受(如果不是更好)的做法,而不是使用forwardRef。 - Andy Corman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接