这就是我尝试用组件的 render()
方法中的元素替换一些字符串的方法。但这失败了,因为我将替换的字符串作为真正的字符串而不是元素获取。
我需要做什么才能将 Link
获取为渲染 Link
元素?现在它只是一个字符串输出。
这是正确的“ react ”方式吗?
return (
<List>
{
elements.map(e => {
return (
<List.Item>
{
links ? links.map(link => {
return e.content.replace(
new RegExp(link.label, 'gi'),
'<Link to="/' + link.id + '">$&</Link> (<Icon name="external" />)'
)
}) : ''
}
</List.Item>
)
})
}
</List>
)
元素
[{
"_id" : "zQS6pXicvXk7K2rZ4",
"content" : "This is a sample text to add some links",
"links" : [
{
"id" : "Dn59y87PGhkJXpaiZ",
"type" : "articles",
"label" : "Sample"
},
{
"id" : "GhkJXpaiZDn59y87P",
"type" : "articles",
"label" : "add"
},
{
"id" : "XpaiZDn5GhkJ9y87P",
"type" : "articles",
"label" : "External"
}
]
}]
最佳答案
试试这个:
首先替换string
通过Link
然后render
string
通过使用dangerouslySetInnerHTML
,它应该可以工作。
检查这个例子:
let data = [{
"_id" : "zQS6pXicvXk7K2rZ4",
"content" : "This is a sample text to add some links",
"links" : [
{
"id" : "Dn59y87PGhkJXpaiZ",
"type" : "articles",
"label" : "sample"
},
{
"id" : "GhkJXpaiZDn59y87P",
"type" : "articles",
"label" : "add"
},
{
"id" : "XpaiZDn5GhkJ9y87P",
"type" : "articles",
"label" : "External"
}
]
}];
var App = () => {
return (
<div>
{
data.map(e => {
return (
<div>
{
e.links ? e.links.map(link => {
return <div dangerouslySetInnerHTML={{ __html: e.content.replace(new RegExp(link.label, 'g'),
'<a href="/' + link.id + '">$&</a> (<Icon name="external" />)'
)}} ></div>
}) : ''
}
</div>
)
})
}
</div>
)
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
关于javascript - ReactJS:如何用 'react-way' 中的新元素替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44717508/