如何使用JavaScript + React处理条件运算符?

时间:2019-05-13 23:14:20

标签: javascript reactjs operators ternary-operator

我有以下JavaScript:

const { inverseDirection } = this.props;

如果inverseDirection为false,则需要以下内容:

const dashOffset =
  dashArray - (dashArray * this.state.percentProgress) / 100;

如果inverseDirection为true,则需要以下内容:

const dashOffset =
  dashArray + (dashArray * this.state.percentProgress) / 100;

在不重复整行的情况下优雅地编写代码的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

你可以

const dashOffset = inverseDirection 
? ( dashArray + (dashArray * this.state.percentProgress) / 100) 
: (dashArray - (dashArray * this.state.percentProgress) / 100)

并不是那么优雅,但是任何更复杂的事情都会浪费时间,而且可能不太可读。

答案 1 :(得分:1)

您可以尝试以下方法:

const { inverse } = this.props;

let calc = (x, y) => (x * y) / 100

let offset = arr + (inverse ? -1 : 1)*(calc(arr, this.state.percentProgress))

这样,您可以提取/重用calc函数(或移至utils等),而inverse操作可以归结为一个简单的inverse ? -1 : 1真的在追。