【问题标题】:Accessing child refs without passing it from parent在不从父级传递的情况下访问子级引用
【发布时间】:2019-03-22 11:43:54
【问题描述】:

我知道我可以像这样访问孩子的 ref

ParentComponent extends React.Component {

  constructor() {
    this.myRef = React.createRef();
  }


  render() {
    return (
    <ChildComponent>
      <div ref={myRef}>Blah</div>
    <ChildComponent>
    );
  }
}

ChildComponent extends React.Component {

  render() {
    const {children} = this.props.children;
    console.log(children.ref) // Will get DOM element
    return {children}
  }
}

但是有没有办法在不从父组件传入 ref 的情况下获取 DOM 元素,以便我的子组件可以从 this.props.children 获取 ref?

在高层次上,我正在尝试制作一个可扩展的组件 ChildComponent,以便每个使用 ChildComponent 的父组件都不必为子组件声明 refs。

【问题讨论】:

  • 这听起来像是你在以非 React 的方式做某事。你能详细介绍一下这个可扩展组件应该做什么吗?
  • 当然。我有一个工具提示组件,我想在文本标签上显示它,我希望它仅在文本溢出它包含的 div 时显示。我目前的解决方案是检查溢出的灵感来自 stackoverflow.com/questions/42012130/…
  • 听起来您可以使用渲染道具:&lt;TooltipOnOverflow tooltip={&lt;Tooltip text={text} /&gt;}&gt;{text}&lt;/TooltipOnOverflow&gt; 并在此组件中具有溢出检查逻辑(例如,它可以使用 &lt;div&gt; 包装 this.props.children),然后具有它会在需要时呈现 tooltip 道具。
  • 我对渲染道具不太熟悉,但从你的例子来看,这是否意味着我必须用 包装每个工具提示?好像会变得乱七八糟

标签: reactjs


【解决方案1】:

在这里找到答案Getting DOM node from React child element

答案有点老了,所以我用回调引用重写了一点,而不是使用 findDOMNode (https://github.com/yannickcr/eslint-plugin-react/issues/678)。

ParentComponent extends React.Component {
  constructor() {
    this.myRef = React.createRef();
  }

  render() {
    return (
    <ChildComponent>
      <div ref={myRef}>Blah</div>
    <ChildComponent>
    );
  }
}

ChildComponent extends React.Component {

  constructor() {
    this.myElement = null;
    this.myRef = element => {
      this.myElement = element;
    };
  }

  render() {
    const {children} = this.props.children;
    return (
    <div> 
     {React.cloneElement(children, { ref: this.myRef})};
    </div>
    )
  }
}

注意:以上仅适用于子组件只有来自父级的子组件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2017-08-31
    • 1970-01-01
    • 2020-12-19
    • 2012-08-07
    • 2014-07-13
    • 1970-01-01
    相关资源
    最近更新 更多