我尽量不渲染我的部分代码。我只想在答案正确/不正确时呈现它。一开始只应显示问题和答案。 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/