解决 React 图标在 JavaScript 中显示对象的问题。

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

Solve the problem of react icons showing object inside js

问题

When adding icons inside the js condition, the icon appears as an object only, and the icon does not appear

{!signUp ? `${(<FcGoogle />)}` + "Signin With Google" : `${(<FcGoogle />)} SignUp With Google`}

查看图像描述

英文:

When adding icons inside the js condition, the icon appears as an object only, and the icon does not appear

{!signUp ? `${(&lt;FcGoogle /&gt;)}` + &quot;Signin With Google&quot;: `${(&lt;FcGoogle /&gt;)} SignUp With Google`}

enter image description here

答案1

得分: 1

你不能将组件放在字符串内,因为它们是不返回字符串的函数。你可以移除``符号周围的<FcGoogle />或者(在我看来)更好的做法是:

&lt;button
  className=&quot;btn&quot;
  type=&quot;submit&quot;
  disabled={disabled}
  onClick={handleClick}
&gt;
  &lt;FcGoogle /&gt;
  {!signUp ? &quot;登录&quot; : &quot;注册&quot;} 使用Google
&lt;/button&gt;
英文:

You cannot put components inside a string since they are functions that do not return strings. You could either remove the `` around <FcGoogle /> or (IMO) better:

&lt;button
  className=&quot;btn&quot;
  type=&quot;submit&quot;
  disabled={disabled}
  onClick={handleClick}
&gt;
  &lt;FcGoogle /&gt;
  {!signUp ? &quot;Signin&quot; : &quot;Signup&quot;} With Google
&lt;/button&gt;

答案2

得分: 1

如果我们呈现的图标不会根据signUp的值而改变,解决这个问题的更干净方法是在字符串内部使用三元条件运算符并有条件地呈现文本,如下所示:

export function SignInOrSignUp({ signUp }) {
  return (
    <>
      <FcGoogle /> {`${signUp ? '登录' : '注册'} 使用Google`}
    </>
  )
}

这还具有保持我们的代码 DRY 的附加好处。

英文:

If the icon we render doesn't change depending on the value signUp; a cleaner approach to solve this challenge would be use a ternary inside the string and conditionally render the text like below:

export function SignInOrSignUp({ signUp }) {
  return (
    &lt;&gt;
      &lt;FcGoogle /&gt; {`${signUp ? &#39;Signin&#39; : &#39;Signup&#39;} With Google`}
    &lt;/&gt;
  )
}

This has the added benefit of keeping our code DRY also.

huangapple
  • 本文由 发表于 2023年5月20日 21:30:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295485.html
匿名

发表评论

匿名网友

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

确定