【问题标题】:How to access properties in child from children props in react如何从反应中的儿童道具访问儿童的属性
【发布时间】:2020-06-15 09:31:36
【问题描述】:

标题非常简单,我需要访问通过我的组件的子元素传递的子元素上的属性(准确地说是 ref),这意味着我无法在父 afaik 中传递 ref . 这是一个突出我的问题的最小示例:

import React from "react";

class Child extends React.Component {
  myRef = React.createRef();

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

const Parent = ({ children }) => {
  const myChild = React.Children.toArray(children).find(
    child => child.type === Child
  );
  // I want to access this
  console.log(myChild.myRef);
  // but it's undefined

  return (
    <div>
      <h1>Parent</h1>
      {children}
    </div>
  );
};

// I can't really change this component
export default function App() {
  return (
    <div className="App">
      <Parent>
        <Child />
      </Parent>
    </div>
  );
}

我制作了一个代码框来突出我的问题https://codesandbox.io/s/eloquent-wing-e0ejh?file=/src/App.js

【问题讨论】:

  • 您能详细说明一下您想要实现的目标吗?将 Refs 传递给父组件的机会并不是您真正需要的。
  • @jogesh_pi nope 因为不幸的是 Child 没有设置在 Parent 中
  • @YevgenGorbunkov 我需要在 Parent 中访问 Child 的 dom 元素,因为我需要检查它的高度/scrollPosition 并将其与 Parent 匹配
  • 那么你可以liftheight/scrollPosition同时处理onScroll到你父母的状态。 Refs are not React 中每一扇门的钥匙。如果您想分享一些代码示例更接近您的真实案例,我会建议一些相关代码来解决您的问题。

标签: javascript reactjs


【解决方案1】:

您应该在&lt;Parent/&gt; 中声明 ref 并将其传递给孩子,而不是在 &lt;Child/&gt; 中声明 ref。

import React from "react";

class Child extends React.Component {

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

const Parent = ({ children }) => {
  const myRef = React.useRef(null);

  // access it from here or do other thing
  console.log(myRef);

  return (
    <div>
      <h1>Parent</h1>
      { children(myRef) }
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      <Parent>
        {myRef => (
          <Child myRef={myRef} />
        )}
      </Parent>
    </div>
  );
}

【讨论】:

  • 这个解决方案的问题是我无法更改App
  • 你能告诉我为什么你不能改变你的App吗?
  • 我无权访问它,我的父/子组件是我有权访问的不同项目中的组件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多