ReactJS 中具有相同道具的组件的条件渲染

Conditional Rendering of Components with Same Props in ReactJS

我有一个简单的条件测试,我是运行看看要渲染哪个组件。如果条件为真,我渲染一个组件,为假另一个组件。现在我的代码是这样的:

    {isPresent && (
        <FirstComponent
          propOne="value one"
          propTwo="value two"
          {...props}
        />
    )}
    {!isPresent && (
        <SecondComponent
          propOne="value one"
          propTwo="value two"
          {...props}
        />
    )}

我想知道我是否可以让这段代码更干一点。像这样:

{isPresent && (
    <FirstComponent
        {propList}
    />
)}
{!isPresent && (
    <SecondComponent
        {propList}
    />
)}

其中 propList 代表我想包含在每个组件中的所有道具。

这可能吗?如果是,怎么做?

谢谢。

如果两个元素具有相同的属性,那么您可以将这些属性存储到一个常量中并将其传递给目标组件

function YourComponent(props) {
  const commonProps = {
      propOne: "value one",
      propTwo: "value two",
      ...props
   };

   const Component = isPresent ? FirstComponent : SecondComponent;
   return <Component {...commonProps}/>;
}

您可以在渲染中使用变量来定义要渲染的组件

 let Comp = isPresent ? FirstComponent : SecondComponent
 let propList = {
    propOne :"value one",
    propTwo : "value two",
    ...props
 }

然后在你的return中你可以使用

 <Comp
   { propList }
 />

注意:- 如果要为变量分配一个组件,请始终以首字母大写命名变量,因为 In JSX, lower-case tag names are considered to be HTML tags