检查属性时无法将组件分配给变量

时间:2019-09-16 16:13:37

标签: 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 />
    </>
  )
}

即,我正在尝试查看是否正在使用道具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时呈现它,而在不使用prop时不呈现呢?

2 个答案:

答案 0 :(得分:4)

class ClientViewSet(viewsets.ModelViewSet): """ API endpoint that allows messages to be viewed or edited. """ queryset = ClientUser2.objects.all() serializer_class = ClientNameSerializer 声明为isSet && MyComponent(强制转换)。使用boolean

ternary operator

或者好老的const UseComponent = isSet ? MyComponent : React.Fragment

if

但是通常在像您这样的用例中,我们只使用let UseComponent = React.Fragment if(isSet) UseComponent = MyComponent

conditional rendering

答案 1 :(得分:2)

您也可以这样做

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

  const UseComponent = MyComponent

  return (
    <>
        {isSet && <UseComponent />}
    </>
  )
}