我有一个 React 类,并且渲染函数工作正常。 <li>
标签和内部 <a>
标签渲染。
然而, getListItem
返回的 HTML 字符串不渲染。相反,它在页面上显示为代码,就好像它已被转义一样。
如何在 React 中防止这种行为,以便在创建组件时构建动态 HTML,如下面(尝试的)示例所示?
class ExchangeListItem extends Component {
constructor(props) {
super(props);
this.state = {
};
}
getListItem() {
const retStr = '<a className="nav-link active" href="'+this.props.exchange.url+'">'+this.props.exchange.name + '</a>';
return retStr;
}
render() {
return (
<li>
<a href="https://wwww.google.com">Link</a>
{this.getListItem()}
</li>
);
}
}
这里的具体问题是 React 如何渲染某些内容。如果它是一个字符串,它将转义特殊字符并导致(在本例中)HTML 成为显示文本。另一篇文章只是询问如何更改innerHTML。就我而言,我并不是尝试更改元素,而是尝试让 React 呈现我想要的内容。
最佳答案
在 ES6 中无需解析器执行此操作的另一种更简洁的方法是:
import React from 'react';
class ExchangeListItem extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
getListItem = (exchangeUrl, exchangeName) => (
<a className="nav-link active" href={exchangeUrl}>
{exchangeName}
</a>
);
render() {
return (
<li>
<a href="https://wwww.google.com">Link</a>
{this.getListItem(this.props.exchange.url, this.props.exchange.name)}
</li>
);
}
}
关于javascript - React 似乎在浏览器中渲染之前转义了 HTML,导致它在页面中显示为代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543469/