【发布时间】:2020-07-13 16:13:02
【问题描述】:
在我的 react electron 应用程序中,它使用 API,我接收 JSON 值以将数据显示到组件中。所以例如我有一个Features 组件:
const Features = () => {
const { title } = useSelector(({ titles }) => titles);
let string = title.features;
// the string can contain some html tags. Example bellow:
// sting = 'This is a string containing a href to <a href="www.google.com">Google</a>';
string = string.replace(/href="(.*?)"/g, function() {
return `onClick="${() => shell.openExternal('www.google.com')}"`;
});
return (
<>
<Heading>Features</Heading>
<Text content={parsedHTML} />
</>
);
};
我想要的是用onClick 替换href 属性并分配Electron 的shell.openExternal() 函数。
string.replace() 回调函数会执行此操作,但是当我单击 <a> 元素时,应用会抛出下一个错误:
error: uncaughtException: 预期
onClick监听器是 函数,取而代之的是string类型的值。
更新
也试过这个逻辑,出现同样的错误:
global.openInBrowser = openInBrowser; // openInBrowser is basically a function that calls shell.openExternal(url)
const re = new RegExp('<a([^>]* )href="([^"]+)"', 'g');
string = string.replace(re, '<a$1href="#" onClick="openInBrowser(\'$2\')"');
这是Sandboxrep 的链接。
我该如何正确地做到这一点?
【问题讨论】:
-
试试
onClick="shell.openExternal('www.google.com')" -
@LawrenceCherone 我已经试过了,出现同样的错误
-
那是因为你传递了一个字符串给onClick。只需删除引号,如下所示:'onClick={shell.openExternal('www.google.com')}'
-
@k-wasilewski 是的,我也试过了,也出现同样的错误
标签: javascript reactjs electron