Hi all I am using coffee script and ReactJS for my site. So far I have a smooth development until I encounter String with hashtag and then convert hash tag to react element
大家好我正在为我的网站使用咖啡脚本和ReactJS。到目前为止,我有一个平滑的开发,直到我遇到带有hashtag的String,然后将hash标签转换为react元素
React ELEMENT
@HashtagLink = React.createClass
displayName: 'hashtag link'
render: ->
React.DOM.a null,
href:'/hashtag/' + @props.hashtag
@props.hashtag
JS function
@hashTagToLink = (string) ->
string.replace(/#(\S*)/g,'<a href="http://emilenriquez.com">$1</a>')
Sample String : I am a string with #hashtag I want to be converted to link
示例字符串:我是#hashtag的字符串我想转换为链接
Desired Output: I am a string with #hashtag I want to be converted to link
期望输出:我是#hashtag的字符串我想转换为链接
Current Output: I am a string with <a href="emilenriquez.com">#hashtag</a> I want to be converted to string
当前输出:我是 #hashtag 的字符串我想要转换为字符串
1 个解决方案
#1
0
Your @hashTagToLink
is creating a string suitable for innerHTML
rather than creating a React Element.
你的@hashTagToLink正在创建一个适合innerHTML的字符串,而不是创建一个React Element。
If you want it to return a react element, something like this should work:
如果你想要它返回一个react元素,这样的东西应该工作:
@hashTagToLink = (string) ->
newString = string.split(/#(\S*)/g)
return React.DOM.div(null,
newString[0],
React.DOM.a({
href: 'http://emilenriquez.com'
}, newString[1]),
newString[2],
)
An Alternative: React components also, have a dangerouslySetInnerHTML
method, so if you do need to return the string as a DOM fragment. you can use:
另一种方法:React组件也有一个危险的SetInnerHTML方法,因此如果你确实需要将字符串作为DOM片段返回。您可以使用:
<div dangerouslySetInnerHTML={ __html: @hashTagToLink() } />
https://facebook.github.io/react/tips/dangerously-set-inner-html.html
#1
0
Your @hashTagToLink
is creating a string suitable for innerHTML
rather than creating a React Element.
你的@hashTagToLink正在创建一个适合innerHTML的字符串,而不是创建一个React Element。
If you want it to return a react element, something like this should work:
如果你想要它返回一个react元素,这样的东西应该工作:
@hashTagToLink = (string) ->
newString = string.split(/#(\S*)/g)
return React.DOM.div(null,
newString[0],
React.DOM.a({
href: 'http://emilenriquez.com'
}, newString[1]),
newString[2],
)
An Alternative: React components also, have a dangerouslySetInnerHTML
method, so if you do need to return the string as a DOM fragment. you can use:
另一种方法:React组件也有一个危险的SetInnerHTML方法,因此如果你确实需要将字符串作为DOM片段返回。您可以使用:
<div dangerouslySetInnerHTML={ __html: @hashTagToLink() } />
https://facebook.github.io/react/tips/dangerously-set-inner-html.html