【问题标题】:React element type cannot be coerced to 'string'反应元素类型不能被强制为“字符串”
【发布时间】:2018-03-17 20:10:04
【问题描述】:

我正在尝试对齐 Button 组件中的图标。传递 iconAlign 属性,如果它是正确的,则图标将首先呈现,如果左则文本将稍后呈现,反之亦然。但是我通过流程得到了这个错误

React element `Icon`:  'object type'. See ./tmp/flow/flowlib_16523b66/react.js:159. This type cannot be coerced to 'string'.  

这是我的组件

<ButtonInner>
  {
    iconAlign === 'right' ? `${text} ${icon && <Icon color={iconColor} />}` :
      `${icon && <Icon color={iconColor} />} ${text}`
  }
</ButtonInner>

我错过了什么吗?请问有更好的选择吗?

【问题讨论】:

  • 您不能在字符串文字中使用&lt;Icon&gt; ,它会尝试将对象强制转换为字符串,但它有一个特殊的 toString() 来响应捕获和抛出。重构它以单独处理文本。 iconAlign === 'right' ? ({text} &lt;Icon /&gt;) : (&lt;Icon /&gt; {text}) - 虽然你可以解决基于 CSS 的定位而不是调整项目的顺序。
  • 是的,我明白了。谢谢@DimitarChristoff 我找到了解决方案

标签: reactjs ecmascript-6 flowtype


【解决方案1】:

我不应该使用字符串文字来呈现我的反应组件。我只是将它包裹在一个 div 中,并且效果很好

<ButtonInner>
  {
    iconAlign === 'right' ?
      <div>{text} {icon && <Icon color={iconColor} /></div> :
      <div>{icon && <Icon color={iconColor} />} {text}</div>
  }
</ButtonInner>

本文帮助https://reactjs.org/docs/conditional-rendering.html

【讨论】:

    【解决方案2】:

    字符串文字最终将所有内容都转换为字符串。组件的 toString 由 react 跟踪,当在组件上调用 toString 时会引发错误。您可以编写如下代码来实现相同的效果:

    iconAlign === 'right' ? (
      <Fragment> `${text} ` icon && <Icon color={iconColor} /> </Fragment>) : (
      <Fragment> icon && <Icon color={iconColor} /> {` ${text}`} </Fragment>
    )
    

    如果您使用的是 react 16.2,您可以使用 Fragment 来包裹孩子。你当然可以去老学校,然后添加一个div,但这会在生成的 html 中生成很多非语义 div。

    更多关于Fragments这里:https://reactjs.org/docs/fragments.html

    【讨论】:

    • 如果我必须在文本和图标之间传递孩子怎么办?
    • 快乐@sudheersingh
    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2021-09-27
    相关资源
    最近更新 更多