简体   繁体   English

在反应样式的前置组件中显示样式文本

[英]Display styled text in react styled pre component

I am trying to highlight some text in React pre.我试图在 React pre 中突出显示一些文本。 But, it doesn't seems working.但是,它似乎不起作用。 It shows [object Object] instead of text.它显示[object Object]而不是文本。

 const Text = styled.pre ` color: black; padding-bottom: 10px; `; const HighLight = styled.span ` color: red; `; let obj = [{ id: 123, name: 'abcd', }, { id: 234, name: 'new name', }]; let str = "[123] Hello how are you? [234] and you? [123] Please call me."; obj.forEach(o => { str = str.replace(new RegExp('\\[' + o.id + '\\]', 'gi'), <HighLight>{o.name}</HighLight>); }); console.log(str); render() { return ( <Text> {str}</Text>); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Also I tried following but, same result我也试过,但结果相同

const Text = styled.span `
        color: black;
        padding-bottom: 10px;
    `;

<Text dangerouslySetInnerHTML={{ __html: str }} />

Any help would be greatly appreciated.任何帮助将不胜感激。

As I have mentioned in my comment, you cannot insert React elements into a string because React elements are objects.正如我在评论中提到的,您不能将 React 元素插入到字符串中,因为 React 元素是对象。 Instead you have to somehow parse the string and create a list of React elements instead.相反,您必须以某种方式解析字符串并创建一个 React 元素列表。

In your specific example you can get away with using a regular expression to split the string and map every part to either itself (plain string) or a React element, if it matches the pattern.在您的特定示例中,您可以使用正则表达式将字符串和 map 的每个部分拆分为本身(纯字符串)或 React 元素(如果它与模式匹配)。 We take advantage of the fact that JavaScript includes the delimiter in the result array if we us如果我们使用 JavaScript 在结果数组中包含分隔符这一事实

 function HighLight({children}) { return <strong>{children}</strong>; } let obj = [{ id: 123, name: 'abcd', }, { id: 234, name: 'new name', }]; const elements = "[123] Hello how are you? [234] and you? [123] Please call me.".split(/(\[\d+\])/).map(match => { if (/\[\d+\]/.test(match)) { return ( <HighLight> {obj.find(o => o.id === Number(match.slice(1,-1))).name} </HighLight> ); } return match; }); ReactDOM.render( elements, document.body );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Of course if you change your data structure to use the IDs as property names, then getting the right object would be easier.当然,如果您更改数据结构以使用 ID 作为属性名称,那么获得正确的 object 会更容易。

I would have suggested to use a custom tagged template but I assume that you have no control over the string input.我建议使用自定义标记模板,但我假设您无法控制字符串输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM