【问题标题】:React States to create external link with Window Location urlReact States 使用 Window Location url 创建外部链接
【发布时间】:2020-06-08 07:24:57
【问题描述】:

我有一种情况需要在我的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>

现在我需要将&lt;a target="_blank" href={url}&gt;Url/a&gt; 更改为

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

问题是我在 window.location

上收到此错误

输入 '{ url: string; }' 不能分配给类型 'string'。

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

【问题讨论】:

    标签: javascript reactjs typescript react-hooks use-effect


    【解决方案1】:

    按照警告提示尝试使用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 类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 2021-10-03
      • 1970-01-01
      相关资源
      最近更新 更多