首页 > 解决方案 > 从 this.props.children 中获取值

问题描述

我们如何从this.props.children. 记录了相同的输出后,我可以看到对象的值,但它嵌套在两个级别的反应类中。

React 是否提供任何抽象方法来从该对象中选择值?还是我应该循环它们并一一挑选出来?

用例 - 我正在使用<td>自定义道具制作一个具有可自定义值的通用表。我的目的是检查是否存在<td>相应的更改表行为的某些道具(此行为的范围将在CustomTable类本身中定义)

这是我的自定义表 -

<CustomTable>{this.props.children}</CustomTable>

这就是我打电话的方式

<CustomTable>
    <thead>....</thead>
    <tbody>
        <tr>
          <td customPropEnabled={true}> xyz</td>
        </tr>
    </tbody>
</CustomTable>

编辑

刚刚意识到,由于结构的原因,有两层嵌套<table>。一个用于 type <tbody>,一个用于 type <tr>。那么,是否有任何方法可以从该对象中提取组件值或循环它是唯一的方法?

标签: javascriptreactjs

解决方案


您可以使用React.Children.toArray将 转换children为数组,并递归检查嵌套子项中是否存在td带有customPropEnabledprop 设置为 true 的 a。

例子

const checkForCustomProp = children => {
  let childArray = React.Children.toArray(children);
  let child;
  let hasCustomProp = false;

  for (let i = 0; i < childArray.length; i++) {
    child = childArray[i];
    if (child.type === "td" && child.props.customPropEnabled) {
      return true;
    } else if (child.props && child.props.children) {
      hasCustomProp = checkForCustomProp(child.props.children);
    }
  }

  return hasCustomProp;
};

function CustomTable(props) {
  const { children } = props;
  const hasCustomProp = checkForCustomProp(children);

  return (
    <div>
      <table>{children}</table>
      {hasCustomProp && <div>Has custom prop!</div>}
    </div>
  );
}

ReactDOM.render(
  <CustomTable>
    <thead>....</thead>
    <tbody>
      <tr>
        <td customPropEnabled>xyz</td>
      </tr>
    </tbody>
  </CustomTable>,
  document.getElementById("root")
);
<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>

<div id="root"></div>


推荐阅读