Javascript ReactJS-多行文本区域
我正在尝试使用ReactJS创建多行文本输入字段。我创建了这个组件:Javascript ReactJS-多行文本区域,javascript,html,jinja2,reactjs,Javascript,Html,Jinja2,Reactjs,我正在尝试使用ReactJS创建多行文本输入字段。我创建了这个组件: var TextInput = React.createClass({ getInitialState: function(){ return {currentValue: this.props.children} }, handleChange: function(event){ //handler }, render: function(){ return ( &
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}/>
)
}
});
var TextInput=React.createClass({
getInitialState:函数(){
返回{currentValue:this.props.children}
},
handleChange:函数(事件){
//处理者
},
render:function(){
返回(
)
}
});
我将它呈现为这样:
# jinja2 template
React.render(
<TextInput>{{ post.body }}</TextInput>,
document.getElementById('post-editing')
);
#金甲2模板
反应(
{{post.body}},
document.getElementById('后期编辑')
);
问题是:如果
{post.body}
类似于#Title\n text
,则文本区域将其显示在一行中。我在我的文本区域中看到#标题文本
,没有换行符。使用ReactJS设置值的正确方法是什么 您正在以正确的方式设置
的值,通过value
属性,问题是您获得的作为this.props.children
值的字符串实际上不是您认为的字符串
如果在
组件中输入值为“#Title\n text”
,则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}/>
)
}
render:function(){
var value=this.state.currentValue.replace('\\n','\n');
返回(
)
}
如果通过value
属性指定输入值,则每次重新渲染时都会使用该值呈现文本区域。如果我理解正确,您应该使用defaultValue
var TextInput = React.createClass({
getInitialState: function(){
return {currentValue: this.props.children}
},
handleChange: function(event){
//handler
},
render: function(){
return (
<textarea name="body"
onChange={this.handleChange}
defaultValue={this.state.currentValue} />
)
}
});
var TextInput=React.createClass({
getInitialState:函数(){
返回{currentValue:this.props.children}
},
handleChange:函数(事件){
//处理者
},
render:function(){
返回(
)
}
});
我还应该提到,在React中,在
getInitialState
中使用props
是反模式的,但这是另一个问题。。和。nice,但是this.state.currentValue.split('\\n').join('\n')代码>似乎更合适。此外,它必须在服务器上具有反转替换\n
=>\\n