如何在React的状态中插入复选标志符

huangapple go评论65阅读模式
英文:

How to insert a checkmark symbol into state in React

问题

Am trying to use state to change the symbols on a button based on whether the button has been clicked or not but the state doesn't seem to accept the values unless they are strings

Code in Vs

// this piece of state right here returns an error
const [tick, setTick] = useState($#x2713);

// the state only allows premitive values, so it'll only work if it's a string
const [tick, setTick] = useStata("$#2713");

What's another solution to get to this outcome right here using state....
Code in Vs

英文:

Am trying to use state to change the symbols on a button based on whether the button has been clicked or not but the state doesn't seem to accept the values unless they are strings

Code in Vs

// this piece of state right here returns an error
const [tick, setTick] = useState($#x2713);

// the state only allows premitive values, so it'll only work if it's a string
const [tick, setTick] = useStata("$#2713");

What's another solution to get to this outcome right here using state....
Code in Vs

答案1

得分: 1

您试图使用React来编写HTML实体。这将需要使用dangerouslySetInnerHTML,正如其名称所示,这并不是鼓励的做法。

相反,存储按钮的状态并使用该状态来呈现值:

const [clicked, setClicked] = useState(false);

return (
  <button onClick={() => setClicked(true)}>
    {clicked ? <>&#x2713;</> : <>&times;</>}
  </button>
);

如何在React的状态中插入复选标志符

英文:

You're trying to use React to write an HTML entity. To do so would require dangerouslySetInnerHTML and as the name implies, it's not encouraged.

Instead, store the state of the button and use that state to render values

const [clicked, setClicked] = useState(false);

return (
  &lt;button onClick={() =&gt; setClicked(true)}&gt;
    {clicked ? &lt;&gt;&amp;#x2713;&lt;/&gt; : &lt;&gt;&amp;times;&lt;/&gt;}
  &lt;/button&gt;
);

如何在React的状态中插入复选标志符

huangapple
  • 本文由 发表于 2023年6月15日 07:49:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478260.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定