React-Bootstrap: Why renders the Alert component the text differently if the text is stored inside a state variable?

自闭症网瘾萝莉.ら 提交于 2019-12-23 01:07:33

问题


I am using react-bootstrap that targets Bootstrap v3 and I am using the Alert component to show messages to the user.

Furthermore I need to show messages with multiple lines. For the line break I use <br />.

If I "hard-code" the multiple line text inside the Alert component the component is working as expected showing multiple lines.

But if I use a variable which belongs to the state of the parent component it is not working.

What is the reason for this behavior?

class MyAlert extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: "Hello <br /> world! <br /> This line ..."
    };
  }

  render() {
    return (
      <div>
        <Alert bsStyle="warning">{this.state.message}</Alert>

        <Alert bsStyle="info">
          "Hello <br /> world! <br /> This line ..."
        </Alert>
      </div>
    );
  }
} //MyAlert



Here the output:


回答1:


The second <Alert> with bsStyle set to info is rendering it as HTML not a string. Notice that the quotation marks are being displayed. So, it isn't a string. Whereas, this.state.message is a string so it is not interpreting the <br /> as a line break. Hope that makes sense.

Here is a work around.

<Alert bsStyle="warning">
  <p dangerouslySetInnerHTML={{ __html: this.state.message }}></p>
</Alert>

Hope this helps.



来源:https://stackoverflow.com/questions/53683071/react-bootstrap-why-renders-the-alert-component-the-text-differently-if-the-tex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!