javascript - 从 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>
。那么,是否有任何方法可以从该对象中提取组件值或循环它是唯一的方法?
解决方案
您可以使用React.Children.toArray
将 转换children
为数组,并递归检查嵌套子项中是否存在td
带有customPropEnabled
prop 设置为 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>
推荐阅读
- python - 导入语句中的点表示什么?
- python - Is it possible to club 2 or more Scripts in Python(spyder)?
- java - Java 泛型 - 类型参数“K”不在其范围内;应该实施 X
- arrays - System Verilog 数组缩减陷阱和参数数组
- python - 如何从响应中获取场地 ID
- mysql - 如何使用nodejs,angularjs在index.html中显示来自mysql的特定数据
- import - Idea 无法解析 java.sql.* 符号,注意无法导入
- apache - 如何正确安装 SSL 到我的服务器?
- reactjs - props.history.push() 不重定向
- flask - 如何使用 SQLalchemy 和 Alembic 自动初始化数据库?