[英]ReactJS how to render an HTML object span element within a string
How can I convert an HTML object containing a span element within a string into something that Reactjs can actually render as HTML?如何将包含字符串中的 span 元素的 HTML 对象转换为 Reactjs 可以实际呈现为 HTML 的内容?
To clarify, here's what I have:为了澄清,这是我所拥有的:
let myObject = "apple tree"
I wrote a function that wraps the word apple in a span tag (html object)我写了一个函数,将单词 apple 包裹在 span 标签(html 对象)中
<span style="color: red;">apple</span>tree
my website is displaying:我的网站显示:
[object Object] tree
BUT it should be displaying但它应该显示
apple tree
where "apple" is colored red because it is wrapped in a span其中“苹果”被涂成红色,因为它被包裹在一个跨度中
I'm passing the string into my component like this:我将字符串传递到我的组件中,如下所示:
return (<div>{myObject}</div>)
Not sure how to render this object as actual HTML element, and not sure if I doing dangerouslySetInnerHTML is the best and only option here too不确定如何将此对象呈现为实际的 HTML 元素,并且不确定我是否危险地执行 SetInnerHTML 也是这里最好也是唯一的选择
How about this?这个怎么样?
{<span style="color: red;">{'apple'}</span>tree}
Lemme know if it works.让我知道它是否有效。
If you want to render an HTML object it's just如果你想渲染一个 HTML 对象,它只是
let myObject=<span style="color: red;">apple</span>;
return (<div>{myObject} tree</div>);
if you are doing something like this return (<div>{this.getRedApple()} tree</div>);
如果你正在做这样的事情
return (<div>{this.getRedApple()} tree</div>);
then in your getRedApple()
function you should just return the variable like so:然后在你的
getRedApple()
函数中,你应该像这样返回变量:
let myObject=<span style="color: red;">apple</span>;
return (myObject);
Don't have it like this: return ({myObject})
不要这样:
return ({myObject})
Create component for it为其创建组件
class Apple extends Component {
render() {
return <span color={this.props.style.color} >{this.props.strApple}</span>tree;
}
}
use that component;使用该组件;
const style = { color: 'red' };
const element = <Apple strApple="apple tree" style="style "/>;
And render it并渲染它
ReactDOM.render(
element,
document.getElementById('root')
);
This Question is already answered here.这个问题已经在这里回答了。 Insert value of object into span tag
将对象的值插入 span 标签
Referring to answer of Nitin Dhomse, you can do something like this:参考 Nitin Dhomse 的回答,你可以这样做:
let myObject = "apple tree";
<span id="span" style="color: red"></span>
$("#span").text(myObject);
This will give you the required output.这将为您提供所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.