【问题标题】:parse string from an api to html将字符串从 api 解析为 html
【发布时间】:2019-12-18 21:25:49
【问题描述】:

我有 api 调用将 10 个对象的集合设置为状态数组。以下是该代码的示例:

class Example extends Component {

    constructor(props) {
        super(props);
        this.state = {
            quiz_data: [],

            quiz_answers:[]
        }
    }

    componentDidMount() {
        Axios.get('api call here')
            .then(response => {
                this.setState({ 'quiz_data': response.data });
            })
    }

然后,我像这样映射该状态数组:

this.quizData = this.state.quiz_data.map((item, id) => {
                return (
                    <div key={id}>
                        <h3 className='quiz-question'>{item.Title}</h3>
                        <p>{item.Question}</p>
                    </div>
                )
})

我的问题/问题是,item.question 作为数组中的字符串返回,并以这种方式出现。

所以我最终得到了带有代码的示例文本,而不仅仅是

示例文本

如何让它返回为 html 而不是字符串?

【问题讨论】:

  • console.log(item.Question) 产生什么?
  • 示例数据问题?

    第二个示例数据问题?
  • 我明白了。
    显示为文本?您是否在开发工具的控制台中看到了这个值?
  • 正确。它不解析html标签。我以前从未遇到过这种情况。我想我只是假设它会。那么我该如何转换呢?

标签: arrays json reactjs array.prototype.map


【解决方案1】:

为什么不尝试将 html 设置为危险阅读 here

this.quizData = this.state.quiz_data.map((item, id) => {
                return (
                    <div key={id}>
                        <h3 className='quiz-question'>{item.Title}</h3>
                       <div dangerouslySetInnerHTML={{__html:item.Question}} /> 
                    </div>
                )
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多