javascript - 显示基于三元运算符的元素

标签 javascript reactjs ecmascript-6

我尽量不渲染我的部分代码。我只想在答案正确/不正确时呈现它。一开始只应显示问题和答案。 React 呈现错误的论点“你错了”。状态设置为空。我查了一下,null 不等于 false 也不等于 true。为什么它会渲染任何东西?在用户选择错误/正确答案之前如何不呈现任何内容?代码:

export default class QuoteApp extends Component {
  constructor(props) {
    super(props)

    this.state = {
       index: 0,
       isCorrect: null
    }
  }

  confirmAnswer = () => {
      this.setState({
          index: this.state.index + 1
      })
  }

  handleClick = (e, index) => {
    if (e.target.textContent === data[index].name) {
      this.setState({
        isCorrect: true
      }) 
      } else {
        this.setState({
          isCorrect: false
        })
    }
  }

  render() {
      const { index, isCorrect } = this.state
      console.log(this.state)
    return (
      <div className="QuoteApp">
        <div className={ (this.state.isCorrect ? 'hide' : '') }>
          <Quote index={index}/>
          <Answers index={index}
                 handleClick={this.handleClick}
                 />
        </div>
        {isCorrect ?
        <h1>you're right</h1>
        :
        <h1>you're wrong</h1>}
        <button onClick={this.confirmAnswer}>Confirm</button>
      </div>
    )
  }
}

我要

你是对的 : 你错了 直到用户交互才会消失

最佳答案

使用 && 运算符。你只会在用户交互上看到你是对还是错

{isCorrect !== null && isCorrect && 
        <h1>you're right</h1>}
{isCorrect !== null && !isCorrect && 
        <h1>you're wrong</h1>}

当用户选择答案时,执行类似下面的操作以隐藏引用/答案

使用 && 运算符

    {isCorrect === null && <div className={ (this.state.isCorrect ? 'hide' : '') }>
      <Quote index={index}/>
      <Answers index={index}
             handleClick={this.handleClick}
             />
    </div>}

或三元运算符

 {isCorrect === null ? <div className={ (this.state.isCorrect ? 'hide' : '') }>
      <Quote index={index}/>
      <Answers index={index}
             handleClick={this.handleClick}
             />
    </div> : null}

关于javascript - 显示基于三元运算符的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52360629/

相关文章:

javascript - Angular : radiobuttons stop firing "ng-change" after each one was clicked

javascript 构造函数未正确绑定(bind)

javascript - 使用 reducer 更新状态内的特定值

javascript - 如何使用 webpack 将 ES6+ 代码编译成 ES6?

reactjs - React 中的 HTML 和 ES6 模板文字

javascript - 谁能发现我的 jQuery 代码的问题 - Fancybox

javascript 富文本编辑器

css - 具有样式系统的每个字体大小的管理器行高

javascript - 如何在javascript中将未定义的数组转换为数组字符串

javascript - ES6 代码风格最佳实践