组件页
import React from "react";
const FormatDiv = (props = {}) => {
if (!props.content) {
return null;
}
let urlPattern = /(https?:\/\/|www\.)[a-zA-Z_0-9\-@]+(\.\w[a-zA-Z_0-9\-:]+)+(\/[\(\)~#&\-=?\+\%/\.\w]+)?/g; // eslint-disable-line no-useless-escape
let content = props.content.replace(urlPattern, function(match) {
var href = match;
if (match.indexOf("http") === -1) {
href = "http://" + match;
}
return '<a target="_blank" href="' + href + '">' + match + "</a>";
});
return (
<div
style={{
display: "inline-block",
maxWidth: props.maxWidth ? props.maxWidth : "680px",
maxHeight: props.maxHeight ? props.maxHeight : "300px",
overflowY: "auto"
}}
dangerouslySetInnerHTML={{
__html: content
.toString()
.split("\n")
.join("<br/>")
}}
/>
);
};
export default FormatDiv;
调用页
<div className="contentmessage">
<FormatDivWithUrl
{...{
content: content,
maxHeight: "250px",
maxWidth: "700px"
}}
/>
</div>