【发布时间】:2021-02-15 18:45:33
【问题描述】:
我正在使用 React 和外部 API
我从一个外部 api 接收数据,其中包含 url, 即
sampleText = Ethereum’s original token distribution event, managed by the [Ethereum Foundation](https://messari.io/asset/ethereum)
我想将网址转换为链接:
const turnIntoLink =(text)=>{
const urlFilter = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
return text.replace(urlFilter, (url)=>{
return '<a href="' + url + '">' + url + "</a>";
})
}
turnIntoLink(sampleText)
当我使用上面的代码时,它会正确读取网址但返回
... managed by the [Ethereum Foundation](<a href="https://messari.io/asset/ethereum">https://messari.io/asset/ethereum</a>)
当我将 turnIntoLink 更改为此
const turnIntoLink =(text)=>{
const urlFilter = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
return text.replace(urlFilter, (url)=>{
return <a href={url}>${url}</a>;
})
}
返回
... managed by the [Ethereum Foundation]([object Object])
更新的 CoinDetail.jsx 反映了反向引用的使用
import React from "react";
const CoinDetail = (props) => {
const { profile } = props.details;
const turnIntoLink = (text) => {
const urlFilter = /\[([^\][]*)]\(((?:https?|ftps?|file):\/\/[^()]*)\)/gi;
return text.replace(urlFilter, '<a href="$2">$1</a>');
};
const display = () => {
return (
<div>
<div>
Launch Details:
{turnIntoLink(profile.economics.launch.general.launch_details)}
</div>
</div>
);
};
return <section>{profile ? display() : "Loading"}</section>;
};
export default CoinDetail;
我怎样才能让它返回一个实际的 a 元素?
更新:
我能够通过在下面的返回中执行此操作来使其工作
<span
dangerouslySetInnerHTML={{
__html: turnIntoLink(
profile.economics.launch.general.launch_details
),
}}
></span>
它有效,但我觉得这有点 hacky,并且有更好的方法来做到这一点。有吗?
【问题讨论】:
-
当您需要to replace with the whole match 时,您不需要使用回调作为替换参数。有一个
$&反向引用。 -
我知道的唯一方法是拆分和连接字符串,同时在需要时将部分转换为正确的 JSX。不幸的是,我找不到这种方法的参考。
-
github.com/iansinnott/react-string-replace 怎么样?这将使您能够编写
return ( <div> {reactStringReplace(content, /\[([^\][]*)]\(((?:https?|ftps?|file):\/\/[^()]*)\)/gi, (match, x, y) => ( <a href={y}>{x}</a> ))} </div>
标签: javascript reactjs regex