【问题标题】:Can't Assign Component to Variable When Checking for Prop检查道具时无法将组件分配给变量
【发布时间】:2020-01-17 12:32:56
【问题描述】:

此代码有效:

import React from 'react'
import { MyComponent } from './components'


export const NewComponent = props => {
  const {
    isValid,
  } = props

  const UseComponent = MyComponent

  return (
    <>
        <UseComponent />
    </>
  )
}

但是这段代码工作:

import React from 'react'
import { MyComponent } from './components'


export const NewComponent = props => {
  const {
    isSet,
  } = props

  const UseComponent = isSet && MyComponent

  return (
    <>
        <UseComponent />
    </>
  )
}

即,我正在尝试查看是否正在使用道具 isSet。如果正在使用它,那么我想渲染组件。如果不是,那就不是。

但是当我尝试将其分配给变量时,我收到以下错误消息:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

有没有办法将我的组件分配给一个变量,以便它在使用道具时呈现,但在不使用时不呈现?

【问题讨论】:

    标签: javascript reactjs react-component


    【解决方案1】:

    isSet &amp;&amp; MyComponent 断言为boolean(强制转换)。使用ternary operator

    const UseComponent = isSet ? MyComponent : React.Fragment
    

    还是好老if

    let UseComponent = React.Fragment
    
    if(isSet) UseComponent = MyComponent
    

    但通常在像您这样的用例中,我们只使用conditional rendering

    return isSet ? <MyComponent /> : null
    

    【讨论】:

    • 做到了 - 谢谢:)。在这种情况下,我不想使用条件渲染,因为我有许多要条件渲染的组件——而且在我的 return 语句中变得有点混乱。
    【解决方案2】:

    你也可以这样做,

    export const NewComponent = props => {
      const {
        isSet,
      } = props
    
      const UseComponent = MyComponent
    
      return (
        <>
            {isSet && <UseComponent />}
        </>
      )
    }
    

    【讨论】:

    • 在这种情况下不需要将组件分配给新变量
    • 是的,你是对的,但可能是 OP 出于其他目的想要重命名组件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2018-12-19
    相关资源
    最近更新 更多