首页 > 解决方案 > React forwardRef 含义

问题描述

我不明白这是什么意思:

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

标签: javascriptnode.jsreactjsecmascript-6

解决方案


从文件

Ref 转发是一种通过组件自动将 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

你可以在这里阅读更多


推荐阅读