简体   繁体   English

<a>使用 JavaScript 打开标签</a>

[英]Open <a> tag using JavaScript

We have a web application where we load the pdf link from BE and open it using JavaScript like this.我们有一个 web 应用程序,我们从 BE 加载 pdf 链接并使用 JavaScript 像这样打开它。

 const openLink = () => {
    window.open("http://www.africau.edu/images/default/sample.pdf", "_blank");
  }

This works fine for the web.这适用于 web。 But we use this same web app in a mobile application as well.但我们也在移动应用程序中使用同样的 web 应用程序。 We have a native android and IOS app which provides a web browser and runs the same web app.我们有一个本机 android 和 IOS 应用程序,它提供了一个 web 浏览器并运行相同的 Z2567A5EC9705EB7AC2C98403 应用程序。 Users won't feel any difference it will work like a normal mobile app.用户不会感觉到任何不同,它会像普通的移动应用程序一样工作。

But for that mobile app doesn't work above code.但是对于该移动应用程序在代码上方不起作用。 A normal <a> tag works fine in the mobile app environment as well.普通的<a>标签在移动应用环境中也可以正常工作。

<a href='http://www.africau.edu/images/default/sample.pdf' target="_blank">Link</a>

Now our goal is to render a normal tag and mimic the native onClick event using JavaScript.现在我们的目标是渲染一个普通标签并使用 JavaScript 模拟原生 onClick 事件。 For some security reason, we cannot directly render the <a> tag with the href instead we set href later using refs.出于某些安全原因,我们不能直接使用href渲染<a>标签,而是稍后使用 refs 设置href But now we need a way to open the link instead of window.open()但是现在我们需要一种方法来打开链接而不是window.open()

This use case may look strange but we have to follow this for some more concerns.这个用例可能看起来很奇怪,但我们必须关注这一点。 This is my current code这是我当前的代码

function App() {

  const tag = useRef();

  const openLink = () => {
    // window.open("http://www.africau.edu/images/default/sample.pdf", "_blank");
    tag.current.href = 'http://www.africau.edu/images/default/sample.pdf' // set the loaded dynamic pdf link from BE
    // open the link code ...
  }

  return (
    <div className="App">
     <button onClick={openLink}>click me</button>
     <a href='' ref={tag} target="_blank" style={{display:"none"}}></a>
    </div>
  );
}

In order to work you must be encapsulating the button inside <a> tag为了工作,您必须将按钮封装在<a>标记

Using style={{display: 'none'}} won't allow you to use the <a> tag使用style={{display: 'none'}}将不允许您使用<a>标签

  const tag = useRef();

  const openLink = () => {
    // window.open("http://www.africau.edu/images/default/sample.pdf", "_blank");
    tag.current.href = "http://www.africau.edu/images/default/sample.pdf"; // set the loaded dynamic pdf link from BE
    // open the link code ...
  };
  return (
    <div className="App">
      <a href="" ref={tag} target="_blank">
        <button onClick={openLink}>click me</button>
      </a>
    </div>
  );

Demo :Demo codesandbox Demo :演示代码框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM