为什么 React.js 在使用标记库时不加载 HTML 代码

IT技术 javascript html reactjs markdown
2021-05-27 10:16:52

我正在尝试构建一个 Markdown 编辑器,我正在为其使用Marked 库 我的代码没有显示任何错误,但根本不呈现 html。

代码 :

class TextArea extends React.Component {
	render() {
		return (
			<div dangerouslySetInnerHTML={{__html: this.props.value}} />
		);
	}
}

class Markdown extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			value: " "
		};
		this.handleChange = this.handleChange.bind(this);
	}
	handleChange(event) {
		this.setState({ value: event.target.value });
	}
	render() {
		return (
			<div>
				<textarea onChange={this.handleChange} />
				<TextArea value={marked(this.state.value,{sanitize: true})} />
			</div>
		);
	}
}

ReactDOM.render(<Markdown />, document.getElementById("markdown"));

我给代码的输入是markdown格式

Heading
=======

Sub-heading
-----------

### Another deeper heading

Paragraphs are separated
by a blank line.

Leave 2 spaces at the end of a line to do a  
line break

Text attributes *italic*, **bold**,
`monospace`, ~~strikethrough~~ .

Shopping list:

* apples
* oranges
* pears
Numbered list:

1. apples
2. oranges
3. pears

The rain---not the reign---in
Spain.
标记库给出的输出是

<h1 id="heading">Heading</h1> <h2 id="sub-heading">Sub-heading</h2> <h3 id="another-deeper-heading">Another deeper heading</h3> <p>Paragraphs are separated by a blank line.</p> <p>Leave 2 spaces at the end of a line to do a<br>line break</p> <p>Text attributes <em>italic</em>, <strong>bold</strong>, <code>monospace</code>, <del>strikethrough</del> .</p> <p>Shopping list:</p> <ul> <li>apples</li> <li>oranges</li> <li><p>pears Numbered list:</p> </li> <li><p>apples</p> </li> <li>oranges</li> <li>pears</li> </ul> <p>The rain---not the reign---in Spain.</p> 

但它不呈现 HTML 请帮助我。提前致谢

1个回答

this.state.value应该是this.props.value因为您value作为以下props发送TextArea

class TextArea extends React.Component {
    render() {
        return (
            <div dangerouslySetInnerHTML={{__html: this.props.value}} />
        );
    }
}