首页 > 解决方案 > 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:字符串;}' 不可分配给类型“字符串”。

我如何解决它?有没有更好的方法将状态链接放在点击事件上?

标签: javascriptreactjstypescriptreact-hooksuse-effect

解决方案


尝试window.location.href=url而不是window.location.href={url}按照警告的建议。

<button
  onClick={e => {
    e.preventDefault();
    window.location.href = url;
  }}
/>

window.location.href={url}将分配一个Object:类型,你应该分配一个类型。{url}.hrefstringstring


推荐阅读