首页 > 解决方案 > 如果在 React 15 中嵌套 2 的最佳方法是什么?

问题描述

我想知道是否可以在 reactjs jsx 中进行嵌套 2 ifs?我尝试了各种不同的方法,但我无法让它工作。我只尝试了一个有效的元素。一旦我放置和元素,我的代码就会中断。

              <div>
                {
                  (() => {
                    if (VerticalRole === "Software Developer")

                    <div>
                      <label>GITHUB ACCOUNT</label>
                      <div className="value">
                        <input
                          type="text"
                          name="github_url"
                          className="lowercase"
                          defaultValue={this.props.talent.github_url}
                          onChange={this.onChangeInput.bind(this)}
                        />
                      </div>
                    </div>

                    if (MarketVetical === "Creative/Marketing")

                    <div>
                      <label>Portfolio Website</label>
                      <div className="value">
                        <input
                          type="text"
                          name="github_url"
                          className="lowercase"
                          defaultValue= 
                          {this.props.talent.personal_website}
                          onChange={this.onChangeInput.bind(this)}
                        />
                      </div>
                    </div>
                  })()
                }
              </div>

标签: javascriptreactjsreact-router

解决方案


您可以尝试使用三元运算符:

<div>
  {
    VerticalRole === "Software Developer" ?
      <div>
        <label>GITHUB ACCOUNT</label>
        <div className="value">
          <input
            type="text"
            name="github_url"
            className="lowercase"
            defaultValue={this.props.talent.github_url}
            onChange={this.onChangeInput.bind(this)}
            />
          </div>
      </div>
    : MarketVetical === "Creative/Marketing" ?
      <div>
        <label>Portfolio Website</label>
        <div className="value">
          <input
            type="text"
            name="github_url"
            className="lowercase"
            defaultValue= 
            {this.props.talent.personal_website}
            onChange={this.onChangeInput.bind(this)}
          />
        </div>
      </div>
    : null
  }
</div>

推荐阅读