【问题标题】:How to conditionally add a prop value if a boolean state value is true如果布尔状态值为真,如何有条件地添加道具值
【发布时间】:2022-08-15 02:30:33
【问题描述】:

如果 addButtonRing 状态值为 true,我正在尝试向按钮添加环。我正在使用反应、打字稿和顺风。

const [addButtonRing, setAddButtonRing] = useState(false);

<button
className={ addButtonRing?`ring-black`:`ring-white` `rounded-xl shadow-md`}>
Button Text
</button>

任何帮助将不胜感激,谢谢!

  • 有什么问题?
  • @AlexRintt 我收到此代码错误
  • 然后向我们展示错误。
  • @AlexRintt 逗号运算符的左侧未使用且没有副作用。这是发布的答案中的错误

标签: reactjs


【解决方案1】:
className={ 
  `rounded-xl shadow-md`,
  (addButtonRing ? `ring-black` : `ring-white`)
}

你去吧。 首先,您错过了 2 个字符串(类)之间的逗号。

其次为三元运算添加括号,以便于理解条件在哪里结束。

现在只需切换按钮,您就会看到类发生了变化。将此添加到您的按钮:

onClick={() => setAddButtonRing(!addButtonRing)}

【讨论】:

  • 谢谢@Hesan,但是我得到了以下错误:逗号运算符的左侧未使用并且没有副作用。ts(2695)JSX表达式可能不使用逗号运算符。你的意思是写一个数组吗?ts(18007)
【解决方案2】:

编写template literal 时,您需要使用${...} 表示法插入变量,如下所示:

<button
  className={`${addButtonRing ? "ring-black" : "ring-white"} rounded-xl shadow-md`}
>
  Button Text
</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 2014-04-25
    • 2014-01-24
    • 2018-08-30
    • 2013-10-04
    • 1970-01-01
    相关资源
    最近更新 更多