2017-05-16 43 views
0

的代碼大塊我有2塊的代碼,我想有條件之間進行切換,我更喜歡在線做,但似乎這個語法是不正確的:內嵌的if-else與JSX

const chunk1 = (...) 
const chunk2 = (...) 

{this.state.condition ? (
    {chunk1} 
) : (
    {chunk2} 
)} 

我得到:

Uncaught Error: Objects are not valid as a React child (found: object with keys {loginOptions}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Card .

什麼是正確的方法?

+1

問題不在於與三元運算符。它與'塊' – Rajesh

+0

當我分別加載每個塊,沒有包裝如果 - 否則他們工作正常 – ilyo

+0

嘗試創建一個函數,根據條件返回必要的塊並在渲染上調用此函數。這也將清理你的渲染方法 – Rajesh

回答

1

我認爲你的語法是錯誤的。試試這個:

{this.state.condition ? 
    chunk1 
: 
    chunk2 
} 

或者

if (condition) { 
    content = chunk1; 
    } else { 
    content = chunk2; 
    } 

{content} 

ES7做:

const content = (data) => do { 
    if (data) chunk1 
    else chunk2 
} 

{content} 

更多信息

Official React documentation for Conditional rendering

+0

是的,塊周圍的{}是不必要的。 – ilyo

+0

是的。很高興我幫了忙。 –

0

我目前想格式化我TERNA像這樣在阿爾·里斯反應:

render() { 
    return (
    <div className="row"> 
     { //Check if message failed 
     (this.state.message === 'failed') 
      ? <div> Something went wrong </div> 
      : <div> Everything in the world is fine </div> 
     } 
    </div> 
); 
} 
0

考慮的代碼塊是JSX元素而已,你可以不喜歡它

class App extends React.Component { 
 
    state = {condition: false} 
 
    
 
    render() { 
 
     var chunk1 = (<div>Hello World</div>) 
 
     var chunk2 = (<div>Hello React</div>) 
 
     return (
 
      <div>{this.state.condition? chunk1 : chunk2}</div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>