【问题标题】:how to get new lines "\n" from string also reflected on the paragraph element如何从字符串中获取新行“\ n”也反映在段落元素上
【发布时间】:2019-01-17 15:02:44
【问题描述】:

我在 React 中有这个 Note 元素来显示用户从文本区域输入的保存的字符串。不知何故,新行没有被空间反射和取代。

我在映射到段落之前检查了字符串,字符串仍然有换行符。但是当它映射到段落时,新行会被空格替换。

如何使新行仍然反映在新创建的段落元素上?下面是我的代码。

class Note extends React.Component {

  render() {
    return (
      this.props.notes.map((note, index) => 
        <div className="note-important" key={index}>
          <p>{note}</p>
        </div>
        )

    ); 

  }
}

class NoteAndDone extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      input: '',
      notes: [],
    }

    this.handleClick = this.handleClick.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.setState({
      input: e.target.value
    })
  }

  handleClick(e) {
    let input = document.getElementById('textarea-note').value;
    if (input && !/^\s*$/.test(input)) {
      this.setState({
        notes: this.state.notes.concat(this.state.input)
      });
    }
  }

  render() {
    return (
      <div className="NoteAndDone">
        <div className="Title">Note</div>
        <textarea id="textarea-note" onChange={this.handleChange} placeholder='Note important things here...' />
        <div className="button-save-container">
          <button className="btn btn-primary" id="button-save-note" onClick={this.handleClick}>Save</button>
        </div>
        <Note notes={this.state.notes}/>
      </div>
    );
  }
}

【问题讨论】:

标签: javascript html string reactjs newline


【解决方案1】:

也许您可以对您的Note 组件进行以下更新?

class Note extends React.Component {

  render() {

    return (
        this.props.notes.map((note, index) => 
            <div className="note-important" key={index}>
              { /* split the note string by \n, filter non-empty lines, and map each resulting line to it's own paragraph element */ }
              { note.split('\n').filterline => !!line).map(line => <p> 
              {{ line }}</p>) } 
            </div>
            )

        ); 

      }
     }

【讨论】:

    【解决方案2】:

    也许您应该用换行符替换换行符? 只需将第 7 行替换为:

    &lt;p&gt;{note.replace("\n","&lt;br /&gt;","g")}&lt;/p&gt;

    虽然您选择不这样做可能有充分的理由......

    【讨论】:

    • 也许不是。我对 React 的体验是通过 React Native 来的,你甚至没有 &lt;p&gt; 组件。我没有办法快速测试这个,所以我真的不能说。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多