Ily*_*nev 8 html javascript jinja2 reactjs
我正在尝试使用ReactJS创建多行文本输入字段.我创建了这个组件:
var TextInput = React.createClass({
getInitialState: function(){
return {currentValue: this.props.children}
},
handleChange: function(event){
//handler
},
render: function(){
return (
<textarea name="body"
onChange={this.handleChange}
value={this.state.currentValue}/>
)
}
});
Run Code Online (Sandbox Code Playgroud)
我这样呈现:
# jinja2 template
React.render(
<TextInput>{{ post.body }}</TextInput>,
document.getElementById('post-editing')
);
Run Code Online (Sandbox Code Playgroud)
问题:如果{{ post.body }}是这样的话#Title \n text,textarea将它显示在一行中.我#Title text在我的textarea 看到没有换行符.<textarea>使用ReactJS 设置价值的正确方法是什么?
Dom*_*tos 16
您正在设置<textarea>正确方式的值,通过该value属性,问题是您获得的字符串this.props.children实际上不是您认为的值.
随着输入值"#Title \n text"在你的<TextInput>组件,价值this.props.children实际上是"#Title \\n text"(注意双反斜线),你需要做类似下面的正确输出换行符:
render: function(){
var value = this.state.currentValue.replace('\\n', '\n');
return (
<textarea name="body"
onChange={this.handleChange}
value={value}/>
)
}
Run Code Online (Sandbox Code Playgroud)