ReactJs如何从父级访问子组件引用

时间:2017-03-10 06:30:00

标签: javascript reactjs react-native

如何访问父项中子项的引用以在父函数中对它们执行某些操作?

   class Parent extends Component {

    function(){
    **//how to access h1 element of child in here ??**
    }
         render() {
          return (
            <Child />
          );
         }
        }

       class child extends Component {
         render() {
          return (
            <h1 ref="hello">Hello</h1>
          );
         }
        }

3 个答案:

答案 0 :(得分:5)

要添加Shubham的答案,必须在父级内的componentDidMount()内访问子引用。类似的东西:

class Parent extends React.Component {
    componentDidMount(){
        var elem1 = this.refs.child1.refs.childRefName;
    }

    return (
    <View>
      <Child1 ref='child1'/>
      <Child2 />
      <Child3 />
    </View>
    );
}

答案 1 :(得分:3)

您可以通过为子元素提供引用并访问子元素来访问子引用,如ReactDOM.findDOMNode(this.refs.child.refs.hello)

在您的情况下,子组件不以您需要更改的大写字母开头。

class App extends React.Component {
   componentDidMount() {
       console.log(ReactDOM.findDOMNode(this.refs.child.refs.hello));
   
   }
   render() {
      return (
        <Child ref="child"/>
      );
     }
    }
class Child extends React.Component {
     render() {
      return (
        <h1 ref="hello">Hello</h1>
      );
     }
    }
    
    
    ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<divi id="app"></div>

答案 2 :(得分:0)

您还可以使用React.forwardingRef方法使Child组件能够从其父级接收并定义ref

以下是该方法的文档:

https://reactjs.org/docs/forwarding-refs.html

下面是如何在代码中实现它的示例:

const Child = React.forwardRef((_, ref) => (
  <h1 ref={ref}>Child Component</h1>
));

function Parent() {
  var h1 = React.createRef();

  React.useEffect(() => {
    console.log(h1.current);
  });

  return <Child ref={h1} />;
}

https://reactjs.org/docs/forwarding-refs.html

希望对您有帮助。