React 中基于状态的条件渲染
IT技术
reactjs
conditional
state
2021-05-01 12:30:21
2个回答
在您的render
方法中,您可以执行以下操作:
render() {
return(
// ... other components
{this.state.error && (
<div className="error-container">
Error:
<p>{this.state.error}</p>
</div>
)}
// ...
)
}
问题是您showError
通过将内容包裹在 ``(反引号)中来创建一个字符串,它不再是 JSX 表达式
使用()
来代替。此外,当您不想返回任何内容时,您应该返回null
而不是空字符串
const showError = this.state.error
? (<div className="error-container">
Error:
<p>{this.state.error}</p>
</div>)
: '';