我正在用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函数可以内联做这件事,或者一个解析东西的方法可以让它工作。


当前回答

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

render(){
    var thisIsMyCopy = (
        <p>copy copy copy <strong>strong copy</strong></p>
    );
    return(
        <div>
            {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

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

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

你可以使用dangerouslySetInnerHTML,例如:

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

试试Fragment,如果你不想要以上任何一种。

在你的情况下,我们可以写信

import React, {useState, Fragment} from 'react'

const thisIsMyCopy = Fragment('<p>copy copy copy <strong>strong copy</strong></p>')

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

如果你使用hook想要在某个条件下设置它的状态

const [thisIsMyCopy, setThisIsMyCopy] = useState(<Fragment><p>copy copy copy <strong>strong copy</strong></p></Fragment>);
import { Fragment } from 'react' // react version > 16.0

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

通过使用“the”将值设置为字符串,React无法知道它是HTML元素。您可以执行以下操作让React知道它是一个HTML元素-

去掉“,它就会工作 使用<Fragment>返回一个HTML元素。