如何在reactjs的render方法中使用三元运算符?

时间:2019-03-15 08:22:43

标签: javascript reactjs

我想使用三元运算符根据某些状态条件渲染两个按钮,只是为了避免代码重复。

我要做什么?

我有两个按钮,分别根据状态值load_cancel取消和开始。如果单击取消按钮,将load_cancel设置为true,并且将load_cancel设置为false,则显示开始按钮。所以我在render方法中有类似的东西

{props.item_id && this.props.load_cancel &&
    <button onClick= 
        {this.props.handle_load_start}>start</button>}
{props.item_id && !this.props.load_cancel  &&
    <button onClick={this.props.handle_load_cancel}>Cancel</button>}

如何使用三元运算符执行相同操作?

谢谢。

3 个答案:

答案 0 :(得分:4)

类似这样的东西

prop.item_id ? (
  this.props.load_cancel ? (
    <button onClick={this.props.handle_load_start}>start</button>
  ) : (
    <button onClick={this.props.handle_load_cancel}>Cancel</button>
  )
) : null

答案 1 :(得分:2)

您可以检查this.props.load_cancel,如果是,则渲染开始按钮,否则渲染取消按钮

{props.item_id && (this.props.load_cancel? <button onClick= 
        {this.props.handle_load_start}>start</button> :
    <button onClick={this.props.handle_load_cancel}>Cancel</button>)}

答案 2 :(得分:0)

您可以这样做:

const { item_id, load_cancel } = this.props; const button = item_id ? ( <button onClick={this.handleClick}>{load_cancel ? 'Start' : 'Cancel'}</button> ) : null;

在handleClick中,您可以根据自己的道具叫this.props.handle_load_startthis.props.handle_load_cancel。 这样,您只需为按钮编写一次jsx。