gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:27:15 26 4
gpt4 key购买 nike

此代码有效:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com