Javascript 确定组件是否是React中功能组件实例的最佳方法
对于我正在构建的组件,我使用Javascript 确定组件是否是React中功能组件实例的最佳方法,javascript,reactjs,react-props,react-component,react-functional-component,Javascript,Reactjs,React Props,React Component,React Functional Component,对于我正在构建的组件,我使用React.Children.map递归地循环其子组件,以修改它们的道具。基本结构如下: //主要组件 const Main=({children})=>递归修改childprops(children); //递归函数 函数递归修改ChildProps(子级){ 返回React.Children.map(Children,(child)=>{ //如果没有有效的react元素,只需返回它 如果(!React.isValidElement(子项)){ 返回儿童; } /
React.Children.map
递归地循环其子组件,以修改它们的道具。基本结构如下:
//主要组件
const Main=({children})=>递归修改childprops(children);
//递归函数
函数递归修改ChildProps(子级){
返回React.Children.map(Children,(child)=>{
//如果没有有效的react元素,只需返回它
如果(!React.isValidElement(子项)){
返回儿童;
}
//检查子项是否不是``组件
//我不确定这张支票
if(typeof child.type!=“string”&&child.type.name==“Main”){
返回儿童;
}
const{children,…restProps}=child.props;
//做一些事情来创造新的道具
const newProps={foo:'bar'};
//使用修改过的道具返回新元素
返回React.createElement(
child.type,
{
…其他道具,
…新道具,
儿童:递归修改儿童道具(儿童)
}
);
});
}
Main
的子组件将通过递归ModifyChildProps
修改其道具,并且他们的子组件将修改其道具,等等。我希望这样做,除非子组件是Main
组件的实例,在这种情况下,应该返回未修改的子组件。目前,我正在通过child.type.name
完成这项工作,这确实有效。然而,我相信这个实现非常容易出现bug,因为每个人都可以将他们的组件称为“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'));
从“React”导入React;
从“react dom”导入react dom;
const Main=({children})=>递归修改childprops(children);
函数递归修改ChildProps(子级){
返回React.Children.map(Children,child=>{
如果(!React.isValidElement(子项)){
返回儿童;
}
if(child.type==Main){
返回未定义;
}
const{children,…restProps}=child.props;
const newProps={foo:'bar'};
返回React.createElement(child.type{
…其他道具,
…新道具,
儿童:递归修改儿童道具(儿童)
});
});
}
常量应用=()=>{
返回(
//跳过v Main
你好
);
};
ReactDOM.render(,document.getElementById('root'));