我正在用React构建一些东西,我需要在JSX中插入带有React变量的HTML。有没有一种方法可以让一个变量像这样:

var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';

然后像这样把它插入react,让它工作?

render: function() {
    return (
        <div className="content">{thisIsMyCopy}</div>
    );
}

并让它按预期插入HTML ?我还没有见过或听说过任何一个react函数可以内联做这件事,或者一个解析东西的方法可以让它工作。


当前回答

你可以使用dangerouslySetInnerHTML,例如:

render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
    );
}

其他回答

您不需要任何特殊的库或“危险”属性。你可以使用React Refs来操作DOM:

class MyComponent extends React.Component {
    
    constructor(props) {
        
        super(props);       
        this.divRef = React.createRef();
        this.myHTML = "<p>Hello World!</p>"
    }
    
    componentDidMount() {
        
        this.divRef.current.innerHTML = this.myHTML;
    }
    
    render() {
        
        return (
            
            <div ref={this.divRef}></div>
        );
    }
}

一个工作样本可以在这里找到:

https://codepen.io/bemipefe/pen/mdEjaMK

为了避免linter错误,我这样使用它:

  render() {
    const props = {
      dangerouslySetInnerHTML: { __html: '<br/>' },
    };
    return (
        <div {...props}></div>
    );
  }

如果还有人降落在这里。使用ES6,你可以像这样创建你的html变量:

render(){
    var thisIsMyCopy = (
        <p>copy copy copy <strong>strong copy</strong></p>
    );
    return(
        <div>
            {thisIsMyCopy}
        </div>
    )
}

dangerlysetinnerhtml有很多缺点,因为它设置在标签内部。

我建议你使用一些react包装器,比如我在npm上找到的。 Html-react-parser做同样的工作。

import Parser from 'html-react-parser';
var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';


render: function() {
    return (
        <div className="content">{Parser(thisIsMyCopy)}</div>
    );
}

非常简单:)

更新

在最新版本中,用法解释如下:

// ES Modules
import parse from 'html-react-parser';

// CommonJS
const parse = require('html-react-parser');
....

//Parse single element
parse('<li>Item 1</li><li>Item 2</li>');

//Parse multiple elements
parse('<li>Item 1</li><li>Item 2</li>');

你也可以像这样在ReactDOM中包含这个HTML:

var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);

ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));

下面是React文档中的两个链接link和link2,可能会有帮助。