javascript - 检查 Prop 时无法将组件分配给变量

标签 javascript reactjs react-component

此代码有效:

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 />
    </>
  )
}

即,我正在尝试查看 Prop 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.

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

最佳答案

isSet && MyComponent 断言为 boolean(强制转换)。使用三元运算符

const UseComponent = isSet ? MyComponent : React.Fragment

或者很好的旧if

let UseComponent = React.Fragment

if(isSet) UseComponent = MyComponent

但通常在像您这样的用例中,我们只使用条件渲染

return isSet ? <MyComponent /> : null

关于javascript - 检查 Prop 时无法将组件分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57960778/

相关文章:

javascript - 无法使用 setstate Hook 复制数组

javascript - 如何在 material-ui 中导入 more-vert 图标以进行 react ?

reactjs - 如何将当前项目传递给函数,以便我可以将其从 react 组件的数组中删除?

reactjs - 想要根据 map() 中对象的点击来填充输入值 : React+Typescript

javascript - 将数据保存到数据库后如何在按钮单击时关闭aspx页面

javascript - 如何调整bxslider垂直对齐

javascript - 对象未出现在 Canvas 主体负载上

javascript - Google Analytics 中的大量直接 View

javascript - OpenComponents 为自定义编译器返回 TEMPLATE_NOT_SUPPORTED_ERROR