3

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

我想做什么?

我有两个按钮 Cancel 和 Start 基于 state value load_cancel。如果单击 Cancel 按钮load_cancel设置为true,当load_cancel设置为falseStart 按钮时显示。所以我在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>}

如何使用三元运算符做同样的事情?

谢谢。

4

3 回答 3

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
于 2019-03-15T08:28:08.870 回答
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>)}
于 2019-03-15T08:26:51.277 回答
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。

于 2019-03-15T09:39:46.233 回答