Javascript ReactJS - 多行文本区域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27864197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReactJS - multiline textarea
提问by Ilya Boltnev
I'm trying to create multi-line text input field with ReactJS. I've created this component:
我正在尝试使用 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}/>
)
}
});
I'm rendering it this way:
我是这样渲染的:
# jinja2 template
React.render(
<TextInput>{{ post.body }}</TextInput>,
document.getElementById('post-editing')
);
The problem: If {{ post.body }}is something like #Title \n text, the textarea show it in one line. I am seeing #Title textin my textarea without line breaks. What is the right way to set <textarea>value with ReactJS?
问题:如果{{ post.body }}是类似的东西#Title \n text,textarea 将它显示在一行中。我#Title text在我的 textarea 中看到没有换行符。<textarea>使用 ReactJS设置值的正确方法是什么?
回答by Dominic Santos
You are setting the value of the <textarea>the correct way, via the valueattribute, the issue is that the string you are getting as the value of this.props.childrenis actually not what you think it is.
您正在<textarea>通过value属性以正确的方式设置值,问题是您获得的字符串作为值this.props.children实际上并不是您认为的那样。
With an input value of "#Title \n text"in your <TextInput>component, the value of this.props.childrenis actually "#Title \\n text"(notice the double backslash), you need to do something like the following to correctly output the newline character:
"#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}/>
)
}
回答by ColCh
If you specify your input value via valueattribute then it textarea will be rendered with that value on every rerender. Instead, you should use defaultValue, if I understood correctly.
如果您通过value属性指定输入值,则每次重新渲染时都会使用该值渲染 textarea。相反,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} />
)
}
});
Also I should mention that in React, using propsin getInitialStateis antipattern, but this is other question .. and explained in official documentation.
另外我应该提到,在 React 中,使用propsingetInitialState是反模式,但这是另一个问题……并在官方文档中进行了解释。

