如何在父组件中获取子组件 render 的返回值呢?

2018-11-08 13:41:57 +08:00
 azh7138m

想在 content 之间插入一些内容,但是要怎么在父组件中判断子组件的渲染结果是不是 null 呢?

代码类似

https://codesandbox.io/s/k9nr4pqz9r

function LI({ show = true }) {
  if (show) {
    return <span>content</span>;
  }
  return null;
}

function UL({ children }) {
  let ret = [];
  React.Children.forEach(children, (child, index) => {
    if (true /* how to get child render result ? */) {
      ret.push(child);
      ret.push(" * ");
    }
  });
  if (ret.length) {
    ret.pop();
  }
  return ret;
}

function App() {
  return (
    <>
      <UL>
        <LI />
        <LI />
        <LI />
        <LI />
      </UL>
      <hr />
      <UL>
        <LI />
        <LI show={false} />
        <LI />
        <LI />
      </UL>
    </>
  );
}

so 链接: https://stackoverflow.com/questions/53201879/how-do-i-determine-in-the-parent-component-whether-the-rendering-result-of-the-c

2326 次点击
所在节点    React
4 条回复
lijsh
2018-11-08 14:13:02 +08:00
子组件上的 show 属性也应该来自父组件吧
azh7138m
2018-11-08 15:58:11 +08:00
@lijsh 是来自祖先,并不是 UL 传给他的,这里只是一个示例,实际可能不是这个属性
lijsh
2018-11-08 16:06:44 +08:00
@azh7138m #2 那你用 render props,由子组件决定怎么渲染,父组件只管传父组件内的属性过去。
azh7138m
2018-11-08 18:53:23 +08:00
@lijsh render props 是父组件向子组件传入 render,和这个需求没关系,在 UL 里面还是没法知道 render 的结果。
今天翻了一下源码,在 react dom 渲染之前应该是拿不到 render 结果,react 只维护状态。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/505747

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX