小编典典

如何访问父组件中子组件的引用

reactjs

如果我有类似的东西

<Parent>
  <Child1 />
  <Child2 />
  <Child3 />
</Parent>

我想从Child2我拥有的地方访问refs="child2refs",该怎么办?


阅读 191

收藏
2020-07-22

共1个答案

小编典典

推荐用于16.3之前的React版本

如果无法避免,那么从React文档中提取的建议模式将是:

import React, { Component } from 'react';

const Child = ({ setRef }) => <input type="text" ref={setRef} />;

class Parent extends Component {
    constructor(props) {
        super(props);
        this.setRef = this.setRef.bind(this);
    }

    componentDidMount() {
        // Calling a function on the Child DOM element
        this.childRef.focus();
    }

    setRef(input) {
        this.childRef = input;
    }

    render() {
        return <Child setRef={this.setRef} />
    }
}

家长 转发绑定到一个功能道具 家长 this。当呼叫作出反应的 儿童的 ref道具setRef也将分配
孩子的 ref父母的 childRef财产。

建议用于React> = 16.3

引用转发是一种选择加入功能,它使某些组件可以接收它们收到的引用,并将其进一步向下传递(即“转发”)给孩子。

我们创建 的组件 可以转发他们refReact.forwardRef。返回的 Component ref
prop必须与的返回类型相同React.createRef。每当React装入DOM节点current时,ref创建的with的属性都React.createRef将指向基础DOM节点。

import React from "react";

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

class AutoFocus extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
    this.onClick = this.onClick.bind(this);
  }

  componentDidMount() {
    this.childRef.current.focus();
  }

  onClick() {
    console.log("fancy!");
  }

  render() {
    return <LibraryButton onClick={this.onClick} ref={this.childRef} />;
  }
}

转发参考HOC示例

创建的 组件 将其转发ref到子节点。

function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);
    }

    render() {
      const {forwardedRef, ...rest} = this.props;

      // Assign the custom prop "forwardedRef" as a ref
      return <Component ref={forwardedRef} {...rest} />;
    }
  }

  // Note the second param "ref" provided by React.forwardRef.
  // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
  // And it can then be attached to the Component.
  return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;
  });
}

请参阅React文档中的转发参考

2020-07-22