【问题标题】:How to make react child component using conditional如何使用条件做出反应子组件
【发布时间】:2020-01-23 12:44:14
【问题描述】:

所以通常我们使用代码创建 react 的子组件看起来像这样:

const component =(<button>Bla Bla</button>)

如何使用条件来创建它?我得试试这个:

const component =(()=>{
if(true){
return(<button>Bla Bla</button>)
}else{
return  null
}
})

但是该代码抛出错误:函数作为 React 子级无效。如果您返回一个组件而不是从渲染中返回,则可能会发生这种情况。或者,也许您打算调用这个函数而不是返回它。

如何正确编写该代码?

【问题讨论】:

  • 尝试
    值 &&
    。值是状态值或其他东西。你会在 JSX 中使用条件渲染

标签: reactjs


【解决方案1】:

您只需将prop 传递给它即可。使组件像:

const Button = ({ display }) => {
  return <>
   {display && <button>I am Button<button>} 

  </>
}

现在如果你想显示它,你可以把它称为:

<Button display={true} />

希望这对你有用。

【讨论】:

    【解决方案2】:

    你可以这样做

    const component = true ? (<button>Bla Bla</button>): null
    

    true 可以是任何你想检查的条件

    【讨论】:

      【解决方案3】:
          const myComp = ({value}) =>(
            <div>
             {
               value &&
                <myComp />
             }
           <div>
      

      根据我上面的评论。一种方法是在 JSX 代码中使用条件渲染

      【讨论】:

        【解决方案4】:
        const bio = this.state.displayBio ? (
          <div>
            This is true false condition
            <button onClick={this.toggleDisplay}>Show Less</button>
          </div>
        ) : (
          <div>
            <button onClick={this.toggleDisplay}>Show More</button>
          </div>
        );
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-05-07
          • 2020-08-30
          • 1970-01-01
          • 2022-07-26
          • 2015-07-19
          • 2019-03-20
          • 2020-05-18
          相关资源
          最近更新 更多