我正在构建一个用于呈现HTML表单的React组件,并且我发现需要递归遍历我的父Form组件的所有子项,以便仅向某个Type的子组件添加额外的props.
一个例子(在JSX中):
<Form>
<p>Personal Information</p>
<Input name="first_name" />
<Input name="last_name" />
<Input name="email" />
<Label>
Enter Your Birthday
<Input name="birthday" type="date" />
</Label>
</Form>
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我在我的Form组件中使用React.Children.map,然后在map函数中我正在检查孩子的"type"和孩子的"type.displayName"来确定我正在处理的元素(本机HTML元素或ReactElement):
var newChildren = React.Children.map(this.props.children, function(child) {
if (is.inArray(child.type.displayName, supportedInputTypes)) {
var extraChildProps = {
alertColor: this.props.alertColor,
displayErrors: this.state.displayErrors
}
return React.cloneElement(child, extraChildProps);
} else {
return child;
}
}.bind(this));
Run Code Online (Sandbox Code Playgroud)
我的问题是React.Children.map只是通过this.props.children进行了浅层迭代,我希望它还能检查孩子的孩子等等.我需要只为我的Input组件添加道具,以便他们知道何时显示错误,以及应显示错误消息的颜色等.在上面的示例中,生日输入不会收到必要的道具,因为它包含在Label组件中.
React.Children.map的任何计划都有一个"递归"模式或任何其他实用程序可以完成我正在尝试做的事情?
在一天结束时,我想编写一个函数来映射每个孩子(甚至是嵌套的孩子),以便对它进行操作(在这种情况下是克隆).
reactjs ×1