错误:在将 HTML 注入 react 组件时,只能设置“child”或“props.dangerouslySetInn



我正在尝试将一些 HTML 注入到 React 组件中(是的,它很干净(,但出现错误:

Can only set one of `children` or `props.dangerouslySetInnerHTML`

但是我不确定这如何应用于此代码:

        <div className='pure-u-1' style={{ height: '300px' }}>
            <div className='blog-list-item-container' style={heroStyle}>
                <a as={`/post/${this.props.blogObject.slug}`} href={`/post?id=${this.props.blogObject.slug}`}>
                    <button className='blog-button' style={buttonStyle} />
                </a>
                <h1 className='pure-u-md-16-24 pure-u-sm-20-24 blog-list-title' ref={(titleElement) => this.titleElement = titleElement} style={{ marginTop: this.state.titleTop, height: this.state.titleHeight }}>{this.props.blogObject.title}</h1>
            </div>
            <div dangerouslySetInnerHTML={this.createMarkup(testLine)} /> 
        </div>

我只设置dangerouslySetInnerHTML一次。

createMarkup函数:

createMarkup(stringToConvertToHtml) {
    return { __html: stringToConvertToHtml }
}

testLine

const testLine = '<h3>All you need is X, Y, and center</h3><p>Every single visual element that you will use to build your application has coordinates built into it:</p>'
目前还

不清楚错误是什么,因为我想它是在createMarkup调用中。 确保您的 createMarkup 返回一个对象,其中包含 __html 属性和建议标记的字符串值。 此外,请尝试删除 div 标记之间的空格。

createMarkup(testLine) {
 return { __html: '<div>your markup here</div>'}
}

我是这样做的。

<div className={styles.activityContent} dangerouslySetInnerHTML={{ __html: this.markDown( item.title ) }}>

这是我的功能。

markDown(text){
if(text){
  //Here I replace special chars for html tags, this is the example: __ Text in bold __
  return text.replace(/__(.*?)__((_+|W+|$))/g, '<strong>$1</strong>$2');
}

}

相关内容

最新更新