3 回答
TA贡献1806条经验 获得超8个赞
您需要将电话号码替换为链接,然后用于dangerouslySetInnerHTML添加到 React 组件。
注意:dangerouslySetInnerHTML之所以调用它,是因为您容易受到来自用户生成内容的 XSS 攻击。您应该先对琴弦进行消毒。
const Linkify = ({ text, pattern, formatter }) => {
const __html = text.replace(pattern, formatter);
return <div dangerouslySetInnerHTML={{ __html }} />;
};
const text = 'This is my phone number - 1234567890';
const pattern = /\d+/g;
const formatter = str => `<a href="#${str}">${str}</a>`;
ReactDOM.render(
<Linkify text={text} pattern={pattern} formatter={formatter} />,
root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
不使用dangerouslySetInnerHTML主要问题是将字符串分解为链接/非链接字符串。这可以通过使用此答案中的代码来完成。我更新了代码以将字符串标记为匹配项,因此您可以相应地设置它们的格式。
const Linkify = ({ text, pattern, formatter }) => {
const arr = getSegments(pattern, text);
return arr.map(formatter);
};
const text = 'This is my phone number - 1234567890, and his is 34234123142';
const pattern = /\d+/g;
const formatter = ({ text, match }) => match ? <a href={`#${text}`}>{text}</a> : text;
ReactDOM.render(
<Linkify text={text} pattern={pattern} formatter={formatter} />,
root
);
function getSegments(rex, str) {
const segments = [];
let lastIndex = 0;
let match;
rex.lastIndex = 0; // In case there's a dangling previous search
while (match = rex.exec(str)) {
if (match.index > lastIndex) {
segments.push({ text: str.substring(lastIndex, match.index) });
}
segments.push({ text: match[0], match: true });
lastIndex = match.index + match[0].length;
}
if (lastIndex < str.length) {
segments.push({ text: str.substring(lastIndex) });
}
return segments;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
TA贡献1842条经验 获得超12个赞
您真的不想将“字符串”设置为const newString,我会称其为元素。你可以这样做:
const phoneEl = (
<a href="#">
{number}
</a>
);
哪里number是存储在一个名为变量的电话号码number。
然后你会写:
<p>My phone number is - {phoneEl}</p>
我也建议
<href={`tel:${number}`}>
如果您希望人们能够单击链接并拨号。
TA贡献1871条经验 获得超13个赞
const string = document.querySelector("body");
const text = string.innerText;
const textArr = text.split(" ").map(item => {
if(item.match(/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im)){
item = `<a href="tel:${item}">${item}</a>`;
}
return item;
});
const newText = textArr.join(" ");
console.log({ newText })
string.innerHtml = newText;
<p class="body">
This is my phone number - 555-555-5555
</p>
添加回答
举报