小编典典

ReactJS-多行文本区域

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

我是这样渲染的:

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

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


阅读 453

收藏
2020-07-22

共1个答案

小编典典

您正在<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}/>
      )
    }
2020-07-22