有没有一种方法可以迭代React中的所有子组件



有没有一种方法可以迭代React中的所有子组件?我有一个看起来像这样的表格:

<Form>
<FormLine>
<FormItem>
<FormInput/>
</FormItem>
<FormItem>
<FormInput/>
</FormItem>
</FormLine>
<FormLine>
<FormItem>
<FormInput/>
</FormItem>
<FormItem>
<FormInput/>
</FormItem>
</FormLine>
<input type="submit"/>
</Form>

表单组件看起来像这样:

export const Form = ({ info, error, success, children, submit, onSubmit }) => {
const { t } = useTranslation();
const [ disabled, setDisabled ] = useState(true);
useEffect(() => {
if(!submit) return;
const inputs = getChildrenByTypeDeep(children, ['FormInput']);
if(inputs) {
inputs.forEach(i => {
console.dir(i);
// I would like to check the values of the form fields somewhere here
});
}    
}, [ children ]);
return(
<div className='Form'>
{success && <div className='Form-success'>{t(success)}</div>}
{error && <div className='Form-error'>{t(error)}</div>}
{info && <div className='Form-info'>{t(info)}</div>}
{children}
{submit &&
<input
type='submit'
value={t(submit)}
disabled={disabled}
onClick={onSubmit ? onSubmit : null}
/>}
</div>
);
};

在启用FormSubmit组件之前,我需要检查所有FormInput组件是否都有值。为此,我希望能够检查Form组件内所有子输入元素的值更改。我尝试过使用react children实用程序和react保姆包,但都没有在Forms中找到我的FormInput组件。

react儿童利用开发中的工作,而不是生产中的

useEffect(() => {
//if(!submit) return;
console.log('Form changed');
setDisabled(false);
deepForEach(children, child => {
if (child && child.type.name === 'FormInput' && child.props.required) {
const value = child.props.value.trim();
if(!value) setDisabled(true);
}
});    
}, [ children ]);

有人能帮我解决这个问题吗?

所以,在谷歌上搜索了一段时间后,我发现了一篇文章https://mparavano.medium.com/find-filter-react-children-by-type-d9799fb78292它解释了一切!

首先,我需要为我的FormInput组件添加一个特殊的道具:

FormInput.propTypes = {
__TYPE: PropTypes.string,
};
FormInput.defaultProps = {
__TYPE: 'FormInput',
};

在那之后,我可以在构建后通过这个道具过滤孩子:

useEffect(() => {
//if(!submit) return;
console.log('Form changed');
setDisabled(false);
deepForEach(children, child => {
if (child && child.props.__TYPE === 'FormInput' && child.props.required) {
const value = child.props.value.trim();
if(!value) setDisabled(true);
}
});
}, [ children ]);

这是可能的,因为文字字符串值没有缩小。非常感谢迈克尔·帕拉瓦诺的澄清!

遗憾的是,React没有提供递归绕过子代的工具。不使用第三方软件包会有所帮助:(

最新更新