从this.props.children中获取值

时间:2018-07-24 11:15:14

标签: javascript reactjs

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

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

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

这是我的自定义表格-

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

这就是我打电话的方式

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

编辑

刚刚意识到,由于<table>结构的存在,嵌套有两个层次。一种是用于<tbody>类型,另一种是用于<tr>类型。因此,是否有任何方法可以从该对象中选取组件值,或者将其循环通过是唯一的方法?

2 个答案:

答案 0 :(得分:2)

您可以使用React.Children.toArraychildren转换成数组,然后递归检查嵌套子级中是否有td属性设置为true的customPropEnabled

示例

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>

答案 1 :(得分:0)

您可以使用React.Children API。

  

React.Children提供了用于处理this.props.children不透明数据结构的实用程序。