三元运算符中的附加条件

Additional conditions in ternary operator

我想根据状态值显示组件。我的

import React, {Component} from 'react';

import One from './One'
import Two from './Two'
import Three from './Three'

class MyTest extends Component{

    constructor(props){
      super(props);
      this.state = {
          slide: 1
        }
      }

    handleClick=()=>{
        const counter=this.state.slide;
        this.setState({
                slide:counter+1
        })
    }

render(){
    return (
             <div onClick={this.handleClick}>
                {this.state.slide===1 ? <One /> : 
                   {this.state.slide===2 ? <Two /> : <Three /> } }
             </div>     
           )
    }

}

export default MyTest;

我收到错误:对于 {this.state.slide===2 Parsing error: Unexpected keyword 'this' 我做错了什么?

不需要{ and }内部三元

{this.state.slide===1 ? <One /> : 
                   this.state.slide===2 ? <Two /> : <Three /> } 

请注意。我假设您希望 handleclick() 循环 this.state.slide。即 1,2,3,1,2,3,1,2,... 如果是这样,那么您的 handleclick() 逻辑似乎会无限期地递增 this.state.slide。即 1,2,3,4,5,6,7,8,..如果我的想法是正确的,您可能需要更改 handleclick() 方法中的逻辑。

试试这个,希望对你有帮助

handleClick = () => {
  const counter = this.state.slide;
  if (counter == 3) {
    this.setState({
      slide: 1
    });
  } else if (counter <= 2) {
    this.setState({
      slide: counter + 1
    });
  }
}