Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
121 views
in Technique[技术] by (71.8m points)

javascript - Trying to use "if-else" statement in a const for a inline style, failed to compile error

I have an inline style that if true, I want to just display a part of state. But, if it is false, I want to run a function that is contained within a const which will give the definitive style.

However, when making the if-else statement within the const, I am getting a "failed to compile error" and I cannot figure out why.

The const in question is 'gradientChoice'

Any ideas at all?

Inline style:

<div
      className="App"
      style={{
        background: mode === "single" ? firstColorInput : gradientChoice,
      }}
    >

The const function I have:

  const gradientChoice = {
    if (gradientSelected === "linear") {
      `linear-gradient(${degSlider}deg, ${firstColorInput}, ${secondColorInput})`
    } else {
      `radial-gradient(${degSlider}deg, ${firstColorInput}, ${secondColorInput})`
    }
  };

States mentioned in the const:

const [degSlider, setDegSlider] = useState("90")
  const [firstColorInput, setFirstColorInput] = useState("")
  const [secondColorInput, setSecondColorInput] = useState("")
const [gradientSelected, setGradientSelected] = useState("linear")
question from:https://stackoverflow.com/questions/65623483/trying-to-use-if-else-statement-in-a-const-for-a-inline-style-failed-to-compi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code actually defines gradientChoice as an object (that's what = { does) however you can't have an if inside an object-literal.

Instead, use the ternary-operator: <bool-expr> ? <when-true> : <when-false>.

const gradientChoice = ( gradientSelected === "linear" ) ?
    `linear-gradient(${degSlider}deg, ${firstColorInput}, ${secondColorInput})`
    :
    `radial-gradient(${degSlider}deg, ${firstColorInput}, ${secondColorInput})`
;

This can be simplified to this:

const gradientChoice = `${ gradientSelected === "linear" ? "linear-gradient" : "radial-gradient" }( ${degSlider}deg, ${firstColorInput}, ${secondColorInput} )`;

Personally I'd do it like this to reduce the total line-length:

const gradientFunc = gradientSelected === "linear" ? "linear-gradient" : "radial-gradient";

const gradientChoice = `${ gradientFunc }( ${degSlider}deg, ${firstColorInput}, ${secondColorInput} )`;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...