【发布时间】:2021-02-24 23:27:13
【问题描述】:
首先,我有一个类组件(在本例中,我们称它为 DynamicComponent),它不包含子组件,但会动态生成 HTML。 DynamicComponent 的示例渲染函数:
render() {
return (
<div>
<input type="text" name="first" />
<input type="text" name="last" />
</div>
);
}
在一个单独的/父组件(我称之为<Form>)中,我循环遍历子元素并搜索元素,以便在表单上注册它们并对其执行验证。这里的问题是,当它到达函数底部的递归部分(child.type === 'DynamicComponent')时,child.props.children 是未定义的(意料之中,因为我没有将任何子项作为道具传递给 DynamicComponent)。我将如何从运行此getChildInputs 函数的父组件中获取动态呈现的字段?简化函数(它是一个累加函数,传入.reduce()):
getChildInputs = (acc, child) => {
// Find form elements and make note of their validation requirements
if (
typeof child.type === 'string' &&
(child.type === 'input' || child.type === 'textarea')
) {
acc[child.props.id] = {
valid: true,
touched: false,
rules: [],
invalidRules: [],
};
if (child.props.required) {
acc[child.props.id].rules.push('required');
}
if (child.props.type === 'email') {
acc[child.props.id].rules.push('email');
}
if (typeof child.props.match !== 'undefined') {
acc[child.props.id].rules.push('match');
acc[child.props.id].match = child.props.match;
}
if (typeof child.props.maxLength !== 'undefined') {
acc[child.props.id].rules.push('maxLength');
acc[child.props.id].maxLength = child.props.maxLength;
}
}
// Make it a recursive search
if (React.isValidElement(child)) {
React.Children.toArray(child.props.children).reduce(Form.getChildInputs, acc);
}
return acc;
}
Parent() 组件渲染函数:
render() {
return (
<div>
<DynamicComponent />
<AnotherChildComponent>
<input type="text" name="input1" />
<input type="text" name="input2" />
</AnotherChildComponent>
</div>
);
}
因此,在这种情况下,getChildInputs 函数将简化为包含 input1 和 input2 元素的数组,但它不会拾取 first 和 last 元素。有没有办法让我获得元素/组件的实际子项,而不仅仅是依赖 props.children?
【问题讨论】:
标签: javascript reactjs