ReactJS-多行文本区域 [英] ReactJS - multiline textarea

查看:500
本文介绍了ReactJS-多行文本区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ReactJS创建多行文本输入字段.我已经创建了这个组件:

I'm trying to create multi-line text input field with ReactJS. I've created this component:

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}/>
    )
  }
});

我是这样渲染的:

# jinja2 template
React.render(
  <TextInput>{{ post.body }}</TextInput>,                  
  document.getElementById('post-editing')
);

问题:如果{{ post.body }}类似于#Title \n text,则文本区域将其显示为一行.我在文本区域中看到#Title text,没有换行符.用ReactJS设置<textarea>值的正确方法是什么?

The problem: If {{ post.body }} is something like #Title \n text, the textarea show it in one line. I am seeing #Title text in my textarea without line breaks. What is the right way to set <textarea> value with ReactJS?

推荐答案

您正在通过value属性以正确的方式设置<textarea>的值,问题是您将获得的字符串作为值this.props.children的内容实际上不是您认为的那样.

You are setting the value of the <textarea> the correct way, via the value attribute, the issue is that the string you are getting as the value of this.props.children is actually not what you think it is.

<TextInput>组件中输入值为"#Title \n text"时,this.props.children的值实际上是"#Title \\n text"(请注意双反斜杠),您需要执行以下操作才能正确输出换行符:

With an input value of "#Title \n text" in your <TextInput> component, the value of this.props.children is actually "#Title \\n text" (notice the double backslash), you need to do something like the following to correctly output the newline character:

    render: function(){
      var value = this.state.currentValue.replace('\\n', '\n');
      return (
        <textarea name="body"
          onChange={this.handleChange}
          value={value}/>
      )
    }

这篇关于ReactJS-多行文本区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆