2016-11-07 91 views
0

我正在尋找條件渲染我的組件的一些HTML元素。React中HTML元素的條件呈現?

我有一個狀態變量布爾值,它可以是true(想要渲染文本)或false(想要不渲染任何東西)。

內返回參數有關渲染functon,我曾嘗試以下:

{this.state.boolean ? <div><h1>True</h1></div> : <div></div>} 

{this.state.boolean && <div><h1>True</h1></div> || <div></div>} 

但在這兩種情況下,H1元素呈現,無論布爾的狀態!

任何想法?提前致謝。

+4

不應該肯定工作。你可以發佈你的例子的小提琴或提供更多的代碼? – azium

+0

我可以確認三元表達式的作品。你可以檢查你的布爾類型和值嗎? –

回答

0

像這樣的東西不起作用?

class Demo extends React.Component{ 
constructor(props){ 
    super(props); 
    this.state = { 
     boolean: false 
    }; 
} 
render(){ 
    return(
     <div> 
      {this.state.boolean && <div><h1>True</h1></div>} 
     </div> 

    ) 
} 

}

0

我通常做類似如下(H/T乍得其代碼是我偷&修改)

class Demo extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state = { 
      boolean: false 
     }; 
    } 
    render(){ 
     var bool = null; 
     if (this.state.boolean) { 
      bool = (<div><h1>True</h1></div>); 
     } 
     return(
      <div> 
       {bool} 
      </div> 
     ); 
    } 
} 
0

這肯定工程,這聽起來像你已經什麼在做。

檢查bin

https://jsbin.com/qomofonera/edit?html,js,output

class Demo extends React.Component{ 
    constructor(props){ 
    super(props); 

    this.state = { 
     boolean: false 
    }; 
    } 
    render(){ 
    return(
     <div> 
      {this.state.boolean ? <div><h1>True</h1></div> : <div><h1>False</h1></div>} 
     </div> 

    ) 
    } 
} 
0

我通常做的:

outputHTML(boolean) { 
    if(!boolean) return null; 
    return (
     <div> 
     Something you wanted to show if the boolean was present 
     </div> 
    ) 
} 

render() { 
    return (
    <div> 
     {this.outputHTML(this.state.boolean)} 
    </div> 
    ) 
} 

如果你想在HTML有條件地呈現了很多的條件或本質上是複雜的。注意:返回null將不會呈現任何內容。

或者更短,更簡單的版本:

{this.state.boolean && <div><h1>True</h1></div>} 

如果它不能正常工作,請提供更多的背景下,或許有些錯誤信息或東西嗎?