React如何简化此代码

时间:2015-11-19 07:04:17

标签: reactjs

我是React的新手,我想知道是否有办法简化此代码:

原件:

renderSubmitBtn() {
    if (this.state.displaySubmit) {
        if (this.state.submitActive) {
            return <button className="active" ref="submit" type="submit"></button>
        } else {
            return <button ref="submit" type="submit"></button>
        }
    } else {
        return <button ref="submit" type="submit" style={{display: 'none'}}></button>
    }
}

此代码根据当前状态返回提交按钮(具有不同的样式)。

我想要实现的目标:

renderSubmitBtn() {
    const btn = <button ref="submit" type="submit">
    if (this.state.displaySubmit) {
        if (this.state.submitActive) {
            return btn.addClass('active')
        } else {
            return btn
        }
    } else {
        return btn.addStyle({'display': none})
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个。

 renderSubmitBtn() {
     let classname = "", style = {}; 
      if (this.state.displaySubmit){ 
          if(this.state.submitActive) {
             classname = "active";
         }
      } else {
           style = {"display":"none"}
    }
       return <button className={classname} ref="submit" style={style} type="submit">
    }

 renderSubmitBtn() {
       return <button className={this.state.displaySubmit && this.state.submitActive : "active":""} ref="submit" style={!this.state.displaySubmit ? {"display":"none"} : {}} type="submit">
    }