2014-06-22 25 views
1

如何創建一個reactjs組件,該組件將使用另一個組件渲染道具數據。例如 我有一句話說「你好,這是{{name}},你好嗎。」現在我想用reactjs組件替換名稱。 當我嘗試用它顯示爲[對象對象]的組件替換名稱。Reactjs如何將反應組件插入到字符串中,然後渲染

首先編輯:

var sentence = "Hello guys this is {{name}}. How are you."; 

var tag_values = {'name': 'any Name'} 

TagBox將句子和tag_value當道具,並與標籤組件更換標籤。並渲染它

var TagBox = React.createClass({ 
    render: function(){ 
     // replacing the tags with Tag component 
     this.props.sentence = this.props.sentence.replace(tags_values['name'], <Tag \>) 
     return(
      <div> 
       {this.props.sentence} //Issue: This will Print as "Hello guys this is [Object Object]. How are you." 
       // But this should print as "This will Print as Hello guys this is any Name. How are you." 
       // After clicking on "any Name" it should be replaced with input. 
      </div> 
     ); 
    } 
}) 

標籤組件將雙擊代替帶有輸入框的標籤。並再次用輸入框中的數據替換輸入框。 這可以使用狀態來完成。

var Tag = React.createClass({}) 
+0

你能給一些示例代碼?我不明白爲什麼你需要一個React組件來處理字符串。 –

+0

我正在創建一個頁面,向用戶提供一個句子:「你好,這是{{name}},你好嗎?」現在,當用戶點擊姓名時,他/她將會在輸入姓名時得到一個輸入框來輸入姓名,而不是{{姓名}}。現在爲每個這樣的標籤創建標籤組件,它將被tagBox組件添加到句子中。而且這個句子的字符串可以每次都是 –

+0

哦,我看,這是一個更好的描述。你能給你的問題添加一些示例代碼,以便有人可以幫忙嗎?要點:輸入框的值應該存儲在'state'的某個地方,當隱藏''時,它應該被替換爲'state'中存儲的值。 –

回答

9

好吧,假設這是一個字符串,你有輸入,你需要創建一個數組。

var parts = str.split(/\{\{|\}\}/g); 
// => ["Hello guys this is ", "name", ". How are you."] 

奇數項是文字串,偶數部分是括號內的東西。

現在我們將創建一個名爲mapAlternate的幫助函數。這需要一個函數來調用奇數元素,以及一個函數來調用我們數組中的偶數元素。

function mapAlternate(array, fn1, fn2, thisArg) { 
    var fn = fn1, output = []; 
    for (var i=0; i<array.length; i++){ 
    output[i] = fn.call(thisArg, array[i], i, array); 
    // toggle between the two functions 
    fn = fn === fn1 ? fn2 : fn1; 
    } 
    return output; 
} 

現在我們可以做這樣的事情在我們的組件:

render: function(){ 
    var parts = str.split(/\{\{|\}\}/g); 


    // render the values in <strong> tags 
    var children = mapAlternate(parts, 
     function(x){ return <span>{x}</span>; }, 
     function(x){ return <strong>{x}</strong> }); 

    return <div>{children}</div>; 
} 

這給了我們:「好傢伙,這是你怎麼樣。」

+0

謝謝..我在亂搞,你讓我很容易。 –

1

您是否聽說過React String Replace

這是一個無狀態的組件例如:

import replace from 'react-string-replace'; 
const reg = /\{([a-z|A-Z|0-9|\.]+)\}/g; 


const OutputComponent = props => { 
    var str = 'Hello {name}, this is a "Super" component: {Super}'; 
    var output = replace(str, reg, prop => props.replacements[prop]); 

    return <div>{output}</div>; 
} 

// later 
import Super from './Super.jsx'; 
const obj = { 
    Super: <Super />, 
    name: 'John' 
} 

return <OutputComponent replacements={obj} />; 
0

我只是固定react-jsx-parser

你的榜樣這個問題將是:

import JsxParser from 'react-jsx-parser' 

export default class TagBox extends React.Component { 
    render() { 
     const sentence = "Hello guys this is <Tag>name</Tag>. How are you." // simply include the component in your string 
     return(
      <JsxParser components={{ Tag }} jsx={ sentence } /> // identify the component in your string to inject 
     ) 
    } 
}