【问题标题】:How to insert a tag in a string to replace a letter and to customize it?如何在字符串中插入标签以替换字母并对其进行自定义?
【发布时间】:2021-03-30 11:10:02
【问题描述】:

我想插入一个 html 标记以自定义单个字母。问题是结果是[object object]。 什么错误?

const getAndChangeCustomI = (content) => {
    let iIndex = content.indexOf("i");
    let insert = [];
    insert.push(<span className="customLetterI" > I</span>)
    content.slice(0, iIndex) + content.slice(iIndex + 1);
    if (iIndex > 0) {
        return content.substring(0, iIndex) + insert[0] + content.substr(iIndex);
    }
    return insert + content;
}

【问题讨论】:

    标签: html reactjs tags components


    【解决方案1】:

    您正在尝试将字符串与节点数组连接。您应该将返回值构造为节点以保留跨度:

    return <>{content.substring(0, iIndex)}{insert[0]}{content.substr(iIndex)}</>;
    

    【讨论】:

    • 嗨,它也不起作用。我得到的只是 [object object],没有任何字符串。
    • 您确定没有其他影响吗?我可以使用上述建议运行您的代码,并且效果很好:codesandbox.io/s/goofy-saha-7tmch
    • 您好,您的代码运行良好,问题是内容标签中的“dangerouslySetInnerHTML”。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 2016-07-23
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多