问题
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