我想從我的數據庫中顯示內容到反應組件。 內容可以是一個字符串或HTML,我知道陣營真的不喜歡HTML注入...注入動態內容反應
我寫了一個模塊,但它不工作,因爲我想
import $ from "jquery";
import React from 'react'
export default React.createClass({
getInitialState() {
return { content: [] };
},
componentDidMount: function() {
if (this.state.content.length == 0) {
$.get('/content', function(data) {
this.setState({
content: data
})
}.bind(this))
}
},
getValue() {
for (let i = 0; i < this.state.content.length; i++) {
if (this.state.content[i].key == this.props.contentKey) {
return this.data[i].value;
}
}
return this.props.contentKey;
},
render() {
return (<span>{this.getValue()}</span>)
}
})
這個人會轉化<Content contentKey="key"/>
爲<span>value</span>
我想例如
render() {
return (
<div>
{content('key1')}
<img src={content('key2')} />
</div>
)
}
比方說,我的服務器返回
{"key1": "<p>I am key 1 value</p>", "key2": "key2Value.jpg"}
結果應該是這樣的
<div>
<p>I am key 1 value</p>
<img src="key2Value.jpg" />
</div>
而且我不想讓HTML進行轉義