反应状态创建外部 link 与 Window 位置 url
React States to create external link with 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: 字符串; }' 不可分配给类型 'string'.
我该如何解决?有没有更好的方法将状态 link 放在点击事件上?
尝试 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
类型。
我有一种情况需要在 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: 字符串; }' 不可分配给类型 'string'.
我该如何解决?有没有更好的方法将状态 link 放在点击事件上?
尝试 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
类型。