首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在父组件中访问子组件的引用?

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

Stack Overflow用户
提问于 2016-06-05 21:41:14
回答 8查看 203K关注 0票数 87

如果我有这样的东西

代码语言:javascript
复制
<Parent>
  <Child1 />
  <Child2 />
  <Child3 />
</Parent>

我想从Child2访问有refs="child2refs"的地方,我怎么做呢?

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2017-03-02 12:07:39

建议在16.3之前使用React版本

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

代码语言:javascript
复制
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。当React调用Child的 ref setRef时,它将将Child的 ref分配给父级的 childRef属性。

建议用于反应>= 16.3

Ref转发是一个opt特性,它允许一些组件获取它们接收的参考信息,并将其进一步向下传递(换句话说,“转发”它)给一个子组件。

我们创建组件,用React.forwardRef转发它们的ref。返回的组件 ref支柱必须与React.createRef的返回类型相同。每当React挂载DOM节点时,用current创建的ref的属性React.createRef将指向底层DOM节点。

代码语言:javascript
复制
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} />;
  }
}

转发参考特别示例

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

代码语言:javascript
复制
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中的转发参考文献

票数 96
EN

Stack Overflow用户

发布于 2017-09-28 11:12:24

  1. 在子组件中,向需要的节点添加一个ref。
  2. 在父组件中向子组件添加一个参考文件。
代码语言:javascript
复制
/*
* Child component
*/
class Child extends React.Component {
  render() {
    return (
      <div id="child">
        <h1 ref={(node) => { this.heading = node; }}>
          Child
        </h1>
      </div>
    );
  }
}

/*
 * Parent component
 */
class Parent extends React.Component {
  componentDidMount() {
    // Access child component refs via parent component instance like this
    console.log(this.child.heading.getDOMNode());
  }

  render() {
    return (
      <div>
        <Child
          ref={(node) => { this.child = node; }}
        />
      </div>
    );
  }
}

演示:https://codepen.io/itsfadnis/pen/aLWVVx?editors=0011

票数 22
EN

Stack Overflow用户

发布于 2019-06-06 16:44:05

下面是一个示例,将重点放在使用refs的输入(在React 16.8.6中进行了测试):

子组件:

代码语言:javascript
复制
class Child extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return (<input type="text" ref={this.myRef} />);
  }
}

带有子组件的父组件:

代码语言:javascript
复制
class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }
  componentDidMount() {
    this.childRef.current.myRef.current.focus();
  }
  render() {
    return <Child ref={this.childRef} />;
  }
}

ReactDOM.render(
    <Parent />,
    document.getElementById('container')
);

具有this.props.children:的父组件

代码语言:javascript
复制
class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.childRef = React.createRef();
    }
    componentDidMount() {
        this.childRef.current.myRef.current.focus();
    }
    render() {
        const ChildComponentWithRef = React.forwardRef((props, ref) =>
            React.cloneElement(this.props.children, {
                ...props,
                ref
            })
        );
        return <ChildComponentWithRef ref={this.childRef} />
    }
}

ReactDOM.render(
    <Parent>
        <Child />
    </Parent>,
    document.getElementById('container')
);
票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37647061

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档