Reactjs 如何在React中将字符串呈现为HTML
我正在使用axios调用ReactJS中的API。调用成功,但输出如下所示:Reactjs 如何在React中将字符串呈现为HTML,reactjs,Reactjs,我正在使用axios调用ReactJS中的API。调用成功,但输出如下所示: Bitcoin has inspired other alternative currencies such as <a href="https://www.coingecko.com/en/coins/litecoin">Litecoin</a>, <a href="https://www.coingecko.com/en/coins/peercoin">Peercoin<
Bitcoin has inspired other alternative currencies such as
<a href="https://www.coingecko.com/en/coins/litecoin">Litecoin</a>,
<a href="https://www.coingecko.com/en/coins/peercoin">Peercoin</a>
比特币激发了其他替代货币,如
,
如何将其呈现为HTML而不是字符串?。这是我的密码
import React from 'react';
import axios from 'axios';
class API extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
data: []
}
}
componentDidMount() {
axios.get('https://api.coingecko.com/api/v3/coins/bitcoin?localization=false')
.then(res => {
const data = res.data;
console.log(res.data);
this.setState({ data, loading: false })
})
}
render() {
return (
<div>
{this.state.loading ? <p>Loading..</p> :
<p>{this.state.data.description.en}</p>
}
</div>
);
}
}
export default API;
从“React”导入React;
从“axios”导入axios;
类API扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
加载:对,
数据:[]
}
}
componentDidMount(){
axios.get()https://api.coingecko.com/api/v3/coins/bitcoin?localization=false')
。然后(res=>{
常数数据=分辨率数据;
console.log(res.data);
this.setState({data,loading:false})
})
}
render(){
返回(
{this.state.loading?正在加载..:
{this.state.data.description.en}
}
);
}
}
导出默认API;
请参见
render(){
返回(
{this.state.loading?正在加载..:
}
);
}
您可以使用,但顾名思义,这很危险。
有关演示代码,请参见代码段
const root=document.getElementById(“根”);
常量应用=()=>{
const APIData=`比特币激发了其他替代货币,如
,
`;
返回(
);
};
ReactDOM.render(,root)代码>
请发布您尝试过的内容far@MosèRaguzzini:OP发布了到目前为止尝试的代码?@huMptyduMpty没有方法尝试解析响应。所以OP没有试图解决这个问题it@Mos拉古兹尼:哈哈,这就是问题所在!代码中没有试图解决删除
并呈现结果的问题。OP问:“当您将
呈现为html时,如何将呈现为“Litecoin”和“Peercoin”的a href标记替换为“Litecoin”。你可以发布一个答案或者让OP在itOk上发表评论,也许OP指的是呈现的HTML,而不是原始输出。这个解决方案完美地解决了这个问题。感谢humpty dumpty:DOP问:“我如何替换仅用“Litecoin”和“Peercoin”呈现的a href标记”。我误解了这一要求,因为在我的词汇表中,替换仅用“Litecoin”和“Peercoin”呈现的a href标记意味着在呈现之前删除a href标记。你可以很好地形成一个问题,并将其设置为错误的标签。
render() {
return (
<div>
{this.state.loading ? <p>Loading..</p> :
<div dangerouslySetInnerHTML={{__html:this.state.data.description.en}}></div>
}
</div>
);
}