在 JSX 中使用大块代码内联 if-else

Inline if-else with big chunks of code in JSX

我有 2 段代码我想在条件之间切换,我更喜欢内联,但似乎这个语法不正确:

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.

正确的方法是什么?

我认为你的语法有误。试试这个:

{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

我目前喜欢在 React 中像这样格式化我的三元组:

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>
  );
}

考虑到代码块只是 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>