reactjs - React 中的 forwardingRef 与回调 refs 有什么区别?

根据 React.js 官方文档,以下代码是回调引用的示例。

function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

class Parent extends React.Component {
  componentDidMount(props) {
    //Here, this.inputElement in Parent will be set to the DOM node corresponding to the element in the CustomTextInput
    console.log(this.inputElement);
  }
  render() {
    return (
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

这里Parent中的this.inputElement会被设置为CustomTextInput中元素对应的DOM节点。

在转发 ref 的情况下,根据官方文档,

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

//Parent Component
class FancyButtonWrapper extends React.Component {
  constructor(props) {
    super(props);
    this.buttonRef = React.createRef();
  }

  componentDidMount(props) {
    //Here this.ref will point to button element. Because of this reason, ref.current will give the value of button.
    console.log(this.buttonRef.current.getAttribute("data-name"));
  }

  render() {
    return (
      //Here we are passing the ref to the child component.
      <FancyButton ref={this.buttonRef} data-attr="Hello">
        Click me!{" "}
      </FancyButton>
    );
  }
}

在这里,在这种情况下,this.ref 将指向按钮元素。由于这个原因,ref.current 将给出 button 的值。

forwardRefcallbackRefs 有区别吗?在这两种情况下,我们都可以从父节点访问子节点的引用。

最佳答案

我不是专家,但这里有一些值得思考的问题: - 回调 refs 在我们需要动态设置 refs 时使用。 - Forward refs 通常在需要访问子引用时使用。

https://stackoverflow.com/questions/59045294/

相关文章:

flutter - 将 mapEventToState 与传入流一起使用的最佳实践?

angular - ViewChild 与 Directive 获取 ViewContainerRe

hibernate - Spring JPA 审计因多个数据源而失败

android - 无法再在 Android Studio 中运行单独的插桩测试

linkedin - 检索 Linkedin Video Post 的缩略图 (ugcPost AP

angular - 如果我重新分配一个存储 rxjs 订阅的变量,那会取消订阅吗?

python-3.x - 如何在 Python 的 Microsoft O365 日历中将日期作为查

git - 在 CLion 远程工具链中跟踪 git 提交时如何触发 cmake 重新配置

python - 使用 Python Requests 在 postman 中做 post 请求

visual-studio-code - VSCode 个人快捷方式在笔记本编辑器中不起作用