2016-02-24 42 views
1

我想從我的數據庫中顯示內容到反應組件。 內容可以是一個字符串或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進行轉義

回答

2

什麼工作是創建一個類的方法,如下面:

renderEls() { 
    return this.state.content.map(function(el) { 
    return (<div> 
     <p>{el.key1}</p> 
     <img src={el.key2} /> 
    </div>) 
    }); 
} 

然後,在你的組件的渲染方法中,你會想要做這樣的事情:

render() { 
    return <div>{this.renderEls()}</div> 
} 

此外,如果您打算使用React,通常最好將所有內容分解爲各自獨立的組件。

就你而言,創建一個新組件可能不是一個壞主意,你將爲從服務器返回的每個對象呈現一個新組件,並將值作爲道具傳入。

從字符串渲染HTML,陣營給你一個辦法做到這樣這裏概述:https://facebook.github.io/react/tips/dangerously-set-inner-html.html

希望幫助!

1

你可以使用XHR而不是jQuery。

var xhr = new XMLHttpRequest() 
xhr.open("GET", './a.json', true) 

xhr.onloadend() 

而且回調則需要

dangerouslySetInnerHTML={{ __html: content}}