添加换行符javascript

时间:2019-03-26 04:04:29

标签: reactjs

如何在ModalBodContent react组件中添加换行符?

<ModalMain
  ModalBodyContent={`New account created. Enrolment email sent. \n\n Name: ${firstName} ${lastName} \n email: ${email}`}
/>

3 个答案:

答案 0 :(得分:2)

您的代码完美地中断了字符串行,但是您需要在呈现该字符串行的HTML元素中使用CSS样式white-space: pre-wrap;

答案 1 :(得分:1)

2种方式:

您可以在<ModalMain/>内使用dangerouslySetInnerHTML

function render() {
  return <div dangerouslySetInnerHTML={{__html: `New account created. Enrolment email sent. \n\n Name: ${firstName} ${lastName} \n email: ${email}`}} />;
}

或者您可以将ModalBodyContent作为元素传递,并相应地进行渲染:

<ModalMain
  ModalBodyContent={
    <div>
      New account created. Enrolment email sent. 
      <br/><br/>
      Name: {firstName} {lastName} 
      <br/>
      email: {email}
    </div>
  }
/>

也可以这样做:

<ModalMain>
  <div>
    New account created. Enrolment email sent. 
    <br/><br/>
    Name: {firstName} {lastName} 
    <br/>
    email: {email}
  </div>
</ModalMain>

答案 2 :(得分:1)

这取决于您期望传递给ModalBodyContent的内容。

如果您将此道具用作字符串,那么您将无能为力。但是,如果将其用作React.ReactNode,则不仅可以向其中传递字符串,还可以向其中传递任何JSX,包括React.Fragment

<ModalMain
  ModalBodyContent={(
    <React.Fragment>
      New account created. Enrolment email sent.
      <br/>
      <br/>
      {`Name: ${firstName} ${lastName}`}
      <br/>
      {`email: ${email}`}
    </React.Fragment>
/>

要以这种方式使用该组件,ModalMain的内部应该是这样的:

render() {
  return (
    // some complex jsx, possibly...
    {this.props.ModalContent}
    // anything else...;
  )
}