简体   繁体   English

三元运算符不适用于带有 React [Hooks] 的内联 styles

[英]Ternary operator not working with inline styles with React [Hooks]

Basically, I have a state that is a true or false.基本上,我有一个 state 是真还是假。 The state name is DisplayFirstColorPicker. state 名称是 DisplayFirstColorPicker。 If its true, I want the inline style to be the const 'showColorPicker', if its false, it should be the const 'hideColorPicker'.如果它是真的,我希望内联样式是 const 'showColorPicker',如果它是假的,它应该是 const 'hideColorPicker'。

However, when I run the inline Ternary operator, I get a "Failed to compile" error.但是,当我运行内联三元运算符时,我收到“编译失败”错误。

Any idea whats wrong?知道有什么问题吗?

The inline code:内联代码:

State: State:

  const [displayFirstColorPicker, setDisplayFirstColorPicker] = useState(false)

Inline code内联代码

<div class="firstColorPicker" style={{DisplayFirstColorPicker ? {showColorPicker} : {hideColorPicker}}}>

The consts常量

const showColorPicker = {
    display: "block",
  }

  const hideColorPicker = {
    display: "none",
  }

You are doing all kinds of weird stuff here.你在这里做各种奇怪的事情。 You have one too many braces on the outside, and also should not be using object short hand notation like {showColorPicker} which would compile to { showColorPicker: { display: none} }你外面有太多大括号,也不应该使用 object 简写符号,如{showColorPicker}将编译为{ showColorPicker: { display: none} }

style={DisplayFirstColorPicker? showColorPicker: hideColorPicker} style={DisplayFirstColorPicker? showColorPicker: hideColorPicker} should do the trick. style={DisplayFirstColorPicker? showColorPicker: hideColorPicker}应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM