React-Bootstrap:如果文​​本存储在状态变量中,为什么要以不同的方式呈现 Alert 组件的文本? [英] React-Bootstrap: Why renders the Alert component the text differently if the text is stored inside a state variable?

查看:41
本文介绍了React-Bootstrap:如果文​​本存储在状态变量中,为什么要以不同的方式呈现 Alert 组件的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用针对 Bootstrap v3 的 react-bootstrap,我正在使用 Alert 组件向用户显示消息.

此外,我需要显示多行消息.对于换行符,我使用 <br/>.

如果我对 Alert 组件内的多行文本进行硬编码",该组件将按预期工作,显示多行.

但是如果我使用一个属于父组件状态的变量,它就不起作用.

这种行为的原因是什么?

class MyAlert 扩展 React.Component {构造函数(道具){超级(道具);this.state = {message: "Hello <br/> world! <br/> 这一行..."};}使成为() {返回 (<div><Alert bsStyle="warning">{this.state.message}</Alert><Alert bsStyle="信息">你好<br/>世界!<br/>这一行……​​"</警报>

);}}//我的提醒



这里的输出:

解决方案

第二个 将 bsStyle 设置为 info 将其呈现为 HTML 而不是字符串.请注意,正在显示引号.所以,它不是一个字符串.而 this.state.message 是一个字符串,因此它不会将
解释为换行符.希望这是有道理的.

这是一个解决方法.

<p risklySetInnerHTML={{ __html: this.state.message }}></p></警报>

希望这会有所帮助.

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:

解决方案

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.

这篇关于React-Bootstrap:如果文​​本存储在状态变量中,为什么要以不同的方式呈现 Alert 组件的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆