javascript - React States 使用 Window Location url 创建外部链接
问题描述
我有一种情况需要在我的window.location.href='http://url.com'
目前我有以下情况有效
const [url,setUrl] = useState('');
useEffect(() => {
getUrl()
.then(x => x.json())
.then(x => {
const { result } = x;
setUrl(result);
});
});
<a target="_blank" href={url}>Url/a>
现在我需要更改<a target="_blank" href={url}>Url/a>
为
<button onClick={(e): void => { e.preventDefault(); window.location.href={url}}}
问题是我在window.location上收到此错误
输入'{ url:字符串;}' 不可分配给类型“字符串”。
我如何解决它?有没有更好的方法将状态链接放在点击事件上?
解决方案
尝试window.location.href=url
而不是window.location.href={url}
按照警告的建议。
<button
onClick={e => {
e.preventDefault();
window.location.href = url;
}}
/>
window.location.href={url}
将分配一个Object
:类型,你应该分配一个类型。{url}
.href
string
string
推荐阅读
- imap - 有没有办法使用 Python 3 IMAPlib 来检索给定消息的发件人地址和关联的 UID
- android - Android Studio 未解析 MediaMetadataRetriever.getFramesAtIndex(int, int)
- reactjs - Reactjs 表。如何将多个值加入到 1 个单元格中?
- c - 检查元素是否在数组中或不是无限循环
- python - 我无法弄清楚为什么这个返回的列表中有空格
- sql - 有关可执行程序进度的信息 - 可能吗?
- php - 用于复杂 XML 请求的 PHP SOAP 客户端
- javascript - D3 缩放回调
- json - 本地 JSON 文件流到网站
- eclipse - 检测 Eclipse 处于无头模式