javascript - 我如何使用 React (JSX) 编写 else if 结构 - 三元表达式不够表达

标签 javascript reactjs jsx

我想在 React 中编写等价物:

if (this.props.conditionA) {
    <span>Condition A</span>
} else if (this.props.conditionB) {
    <span>Condition B</span>
} else {
    <span>Neither</span>
}

也许吧

render() {
    return (<div>
        {(function(){
            if (this.props.conditionA) {
                return <span>Condition A</span>
            } else if (this.props.conditionB) {
                return <span>Condition B</span>
            } else {
                return <span>Neither</span>
            }
        }).call(this)}
    </div>)
}

但这似乎过于复杂。有没有更好的办法?

最佳答案

为什么说三元表达力不够?

render() {
  return <span>
    {this.props.conditionA ? "Condition A" 
      : this.props.conditionB ? "Condition B" 
      : "Neither"}
  </span>;
}

关于javascript - 我如何使用 React (JSX) 编写 else if 结构 - 三元表达式不够表达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38810843/

相关文章:

javascript - FullCalendar 在事件标题中显示 HTML

javascript - 火狐浏览器中的滚动条

javascript - 将 javascript 方法功能分组到 javascript "class"

javascript - ES6 中类的引入如何改变对象创建?像 React 这样使用类的框架又如何呢?

reactjs - 使用 apollo graphql 响应 firebase 身份验证

javascript - React - 如何解决 : "JSX expression must have parent and expression expected" error in vs code

javascript - 如何在原型(prototype)中捕获点击事件

html - 使用 css 将标题标题对齐到正文组件上方以进行 react 应用程序

javascript - 内联 React JS For 循环分页

javascript - 以编程方式在 React 中添加更多组件