javascript - 确定组件是否是 React 中功能组件实例的最佳方法
问题描述
对于我正在构建的组件,我正在递归地循环其子组件React.Children.map
,以对其道具进行修改。基本结构是这样的:
// main component
const Main = ({ children }) => recursivelyModifyChildProps(children);
// recursive function
function recursivelyModifyChildProps(children) {
return React.Children.map(children, (child) => {
// if no valid react element, just return it
if (!React.isValidElement(child)) {
return child;
}
// check if child isn't a `<Main/>` component
// not sure about this check
if (typeof child.type !== 'string' && child.type.name === 'Main') {
return child;
}
const { children, ...restProps } = child.props;
// do stuff to create new props
const newProps = { foo: 'bar' };
// return new element with modified props
return React.createElement(
child.type,
{
...restProps,
...newProps,
children: recursivelyModifyChildProps(children)
}
);
});
}
的孩子Main
将通过修改他们的道具recursivelyModifyChildProps
,他们的孩子将修改他们的道具等。我想这样做,除非子组件是组件的实例Main
,在这种情况下,它应该不加修改地返回。目前我正在通过 执行此child.type.name
操作,这确实有效。然而,我相信这个实现很容易出错,因为每个人都可以称他们的组件为“Main”。什么是最好的(或至少更好的)方法来确定一个组件是一个实例,一个特定的(功能性)组件,还是它本身的一个实例?
解决方案
您可以通过比较唯一的实例child.type
来验证它。Main
if (child.type === Main) {
return undefined;
}
Main
通过跳过实例修改所有子项的完整示例Main
。
import React from 'react';
import ReactDOM from 'react-dom';
const Main = ({ children }) => recursivelyModifyChildProps(children);
function recursivelyModifyChildProps(children) {
return React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child;
}
if (child.type === Main) {
return undefined;
}
const { children, ...restProps } = child.props;
const newProps = { foo: 'bar' };
return React.createElement(child.type, {
...restProps,
...newProps,
children: recursivelyModifyChildProps(children)
});
});
}
const App = () => {
return (
<Main>
// v Main is skipped
<Main />
<div>Hello</div>
</Main>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
推荐阅读
- bash - 发送选项后有没有办法让zenity窗口不退出?
- excel - 基于 Power Pivot 的数据透视表中的奇数结果
- flutter - 通过小部件构造函数传递数据
- python - 使用 CDSView 过滤后具有组计数的散景 vbar
- java - 正则表达式代码未收集多行匹配模式
- java - JDA:如何检测成员是如何从公会中移除的?
- mysql - MySQL 8.0 工作台错误启动和停止以及选项文件
- informatica - INFORMATICA Traget 平面文件。如何将数据与标题对齐
- php - 在 Doctrine (Symfony 4.4) 中对同一实体字段使用多个过滤器
- spring-boot - Gradle SpringBoot 2.4.2 使用带有标签的 bootBuildImage