【问题标题】:Typescript/React `<span>Text</span>`only writes out the text and not elementTypescript/React `<span>Text</span>`只写出文本而不是元素
【发布时间】:2020-05-27 06:56:34
【问题描述】:

我有一个非常简单的函数,它可以分割一个字符串并在中间放置一个样式跨度,因为我想要一些样式文本,它看起来像这样

splitAndApplyStyledContent(content: string, textType: string, separator: string) {
  const splittedContent = content.split(separator);

  switch (textType) {
    case 'Info':
      return [
        splittedContent[0],
        `<span className="styled-text">${this.getString(Name)}</span>`,
        splittedContent[1],
      ];
    default:
      return content;
  }
}

这里的问题是当我在我的 tsx 文件中调用它时

{ props.myStringManager.splitAndApplyStyledContent(props.myStringManager.getString(infoContent), "Info" , '{X}')}

它也会写出&lt;span className="styled-text"&gt; &lt;/span&gt; 部分,而不是把它变成一个元素并应用样式

为了澄清这个函数是在一个看起来像export default class LocalizationsManager的类中,所以它不是一个组件或类似的东西,它也是一个.ts文件,没有.tsx

【问题讨论】:

    标签: reactjs typescript string-interpolation preact


    【解决方案1】:

    返回一个有效的 JSX,而不是一个数组:

    ...
    return (
      <>
        {splittedContent[0]}
        <span className='styled-text'>{this.getString(Name)}</span>
        {splittedContent[1]}
      </>
    )
    ...
    
    

    【讨论】:

    • 它不允许我这样写来编辑这是一个类中的函数,看起来像 export default class LocalizationsManager {
    • 如果是类组件,放在render函数里面:render() {return&lt;div&gt;/div&gt;;}
    • 你显然想在你的函数中返回 JSX。考虑重构你的代码
    猜你喜欢
    • 1970-01-01
    • 2016-05-09
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多