要用 prevState 来执行后续 setState


  • 0

    回复: #7 打开和关闭电脑

    class Computer extends Component {
      constructor () {
        super()
        this.state = { status: 'off', content: '显示器关了' }
      }
      
      handleClickButton () {
        this.setState({ status: this.state.status === 'off' ? 'on' : 'off' })
        this.setState((prevState) => {
          return { content: prevState.status === 'on' ? '显示器亮了' : '显示器关了' }
        })
      }
      
      render () {
        return (
          <div>
            <Screen showContent={this.state.content} />
            <button onClick={this.handleClickButton.bind(this)}>开关</button>
          </div>
        )
      }
    }
    
    class Screen extends Component {
      static defaultProps = {
        showContent: '无内容'
      }
      
      constructor () {
        super()
      }
      
      render () {
        return (
          <div className='screen'>{this.props.showContent}</div>
        )
      }
    }
    

登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待