如何让textarea中输入多行的数据在p标签中换行?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chancein007/article/details/78526070

我们在用React开发Web项目的过程中,有的时候,我们需要把textarea中输入的多行字符串,在其他的标签中输出来,比如p标签。但是,往往这个时候,在p标签中输出的内容其默认情况下是不换行的。比如下面的代码:

import React,{Component} from 'react';
export default class HelloWorld extends Component{

  constructor(){
    super(...arguments);
    this.state={
      note:"",
    }
  }

  render(){
    return(
    <div className="app" style={{padding:"10px 5px 15px 20px"}}>
          <form id="noter-save-form" method="POST" style={{topPadding:"100px",leftPadding:"100px"}}>
              <textarea id="noter-text-area" style={{height:"100px"}} name="textarea" onChange={(e)=> this.setState({note:e.target.value}) } ></textarea>
              <hr/>
              <label>The input value for Note:</label>
              <hr/>
              <p>{this.state.note}</p>
              <hr/>
           </form>
    </div>
  );
  }
}

下面是其渲染的结果:
这里写图片描述

我们可以看出,其在TextArea中输入的回车换行,在p标签中,压根显示不出来。
那么这个时候,我们应该怎么办?其实解决的方案很简单,代码入下:

import React,{Component} from 'react';
export default class HelloWorld extends Component{

  constructor(){
    super(...arguments);
    this.state={
      note:"",
    }
  }

  render(){
    return(
    <div className="app" style={{padding:"10px 5px 15px 20px"}}>
          <form id="noter-save-form" method="POST" style={{topPadding:"100px",leftPadding:"100px"}}>
              <textarea id="noter-text-area" style={{height:"100px"}} name="textarea" onChange={(e)=> this.setState({note:e.target.value}) } ></textarea>
              <hr/>
              <label>The input value for Note:</label>
              <hr/>
              <p>
              {this.state.note.split('\n').map(function(item) {
                  return (
                    <span>
                      {item}
                      <br/>
                    </span>
                  )
                })} </p>
              <hr/>
           </form>
    </div>
  );
  }
}

从上面的代码可以看出,我们在p标签中渲染的时候,把textarea中输入的\n
换成了br标签。

 {this.state.note.split('\n').map(function(item) {
                  return (
                    <span>
                      {item}
                      <br/>
                    </span>
                  )
                })} 

换完后,UI渲染的效果如下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/chancein007/article/details/78526070
今日推荐