【问题标题】:Switch the button action based on id of a button根据按钮的id切换按钮动作
【发布时间】:2021-05-25 18:58:18
【问题描述】:

我正在尝试根据 ID 更改按钮重定向链接,但我是 NEXT.JS 的新手,我不知道该怎么做。 我知道这个请求应该在渲染之后使用“useEffect”或者需要一个变量来制作像“document.GetElementsbyTagName”这样的东西,但是如何? next.js 没有定义“文档”。

下面是我的示例代码

 <ul className="home-brandstext">
                  <li><button onClick={clickHandle} id="Linkedin"><FontAwesomeIcon icon={faLinkedin}/> LinkedIn</button></li>
                  <li><button onClick={clickHandle} id="Github"><FontAwesomeIcon icon={faGithub}/> GitHub</button></li>
                  <li><button onClick={clickHandle} id="Instagram"><FontAwesomeIcon icon={faInstagram}/> Instagram</button></li>
                  <li><button onClick={clickHandle} id="Skype"><FontAwesomeIcon icon={faSkype}/> Skype</button></li>
                  <li><button onClick={clickHandle} id="Whatsapp"><FontAwesomeIcon icon={faWhatsapp}/> WhatsApp</button></li>
                </ul>     

const clickHandle = () => {
  switch(id) {
    case 'Linkedin' : {
      document.location.href = 'https://linkedin.com/in/gustavo-morilla';
      break;
    }   
  }

【问题讨论】:

    标签: javascript html dom switch-statement next.js


    【解决方案1】:

    onClick 回调接收一个 event 作为参数,可用于检索触发它的目标元素,然后获取其 id

    const clickHandle = (event) => {
        switch(event.target.id) {
            case 'Linkedin' : {
                // Logic to handle `Linkedin` case
                break;
            }  
            // ... 
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要使用验证器 process.browsertypeof window != 'undefined' 关闭您的文档,因为 nextJS 在服务器端渲染,而文档在客户端。

      if(process.browser){
      document.location.href =''
      }
      

      React.useEffect 钩子或 componentDidMount() 方法中使用它

      【讨论】:

      • 这真的可以!我需要更多地研究 next.js 来做到这一点并真正理解每一步。所以上面的答案保持简单。我稍后会尝试你的答案。谢谢!!!
      猜你喜欢
      • 2023-03-28
      • 2015-04-16
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多