Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Can';检查道具时,不要将组件分配给变量_Javascript_Reactjs_React Component - Fatal编程技术网

Javascript Can';检查道具时,不要将组件分配给变量

Javascript Can';检查道具时,不要将组件分配给变量,javascript,reactjs,react-component,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 {
    isValid,
  } = props

  const UseComponent = MyComponent

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

有没有一种方法可以将我的组件分配给一个变量,这样它在使用道具时可以渲染,而在不使用道具时不会渲染?

isSet&&MyComponent
断言为布尔值(强制转换)。使用
三值运算符

const UseComponent = isSet ? MyComponent : React.Fragment
如果

let UseComponent = React.Fragment

if(isSet) UseComponent = MyComponent
但通常在像您这样的用例中,我们只使用
条件呈现

return isSet ? <MyComponent /> : null
返回isSet?:无效的
您也可以这样做

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

  const UseComponent = MyComponent

  return (
    <>
        {isSet && <UseComponent />}
    </>
  )
}
export const NewComponent=props=>{
常数{
伊塞特,
}=道具
const UseComponent=MyComponent
返回(
{isSet&&}
)
}

成功了-谢谢:)。在这种情况下,我不想使用条件呈现,因为我有许多组件是条件呈现的——而且在我的return语句中有点混乱。在这种情况下,不需要将组件分配给新变量是的,您是正确的,但可能出于其他目的想重命名组件。
return isSet ? <MyComponent /> : null
export const NewComponent = props => {
  const {
    isSet,
  } = props

  const UseComponent = MyComponent

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