检查道具时无法将组件分配给变量
Can't Assign Component to Variable When Checking for Prop
此代码有效:
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 时呈现,但在不使用时不呈现?
isSet && 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
你也可以这样做,
export const NewComponent = props => {
const {
isSet,
} = props
const UseComponent = MyComponent
return (
<>
{isSet && <UseComponent />}
</>
)
}
此代码有效:
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 时呈现,但在不使用时不呈现?
isSet && 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
你也可以这样做,
export const NewComponent = props => {
const {
isSet,
} = props
const UseComponent = MyComponent
return (
<>
{isSet && <UseComponent />}
</>
)
}