我建設,我想允許用戶輸入的風格在文本區域,這將影響到另一個元素的風格React.js應用。字符串轉換爲JSON對象在React.js風格標籤使用風格= {}
首先,我有一個排組成,看起來像這樣:
function Row(props) {
return (
<tr>
<td width="50%">
<textarea
style={{}}
value={props.style}
onChange={props.onStyleChange}>
</textarea>
</td>
<td><div className="">Row {props.id+1}</div></td>
</tr>
)
};
我通過rowData列表迭代來填充我的行,它可以在這裏找到:
{this.state.rowData.map(function(row, index) {
return (
<Row
id={row.id}
style={row.style}
onStyleChange={function(e) {this.onStyleChange(e, row.id)}.bind(this)}/>
);
}.bind(this))}
然後在我的onStyleChange功能,我有:
onStyleChange: function(e, id) {
this.state.rowData[id].style = e.target.value;
this.setState(this.state);
}
因此,當用戶輸入數據到textarea,它添加到我的rowData數組中的第i個元素。假設它的第0行,並且用戶在文本區輸入「Hello」,那麼rowData [0] .style =「Hello」。
不過,我想能夠做這樣的事情:style={{props.style}}
我行組件中。但是因爲它目前是一個字符串,它不起作用。我也試過style={JSON.parse(props.style)}
,因爲props.style ='{}',每次添加新行時都會引發錯誤。錯誤讀取Uncaught SyntaxError: Unexpected token f in JSON at position 1
永遠感激的任何幫助。有一個更簡單的方法來做到這一點。謝謝。