【问题标题】:passing values dynamically to href attribute将值动态传递给 href 属性
【发布时间】:2017-11-23 09:45:01
【问题描述】:

在下面粘贴我的 sn-p 作为参考:

getInitialState: function()
{
    return {
        repoLinks: [
            "/reports/interactive/CustomersReport",
            "/reports/interactive/MapReport"
        ]
}
render: function(){
      var repoLinks = this.state.repoLinks;
      repoLinks = repoLinks.map(function(item, index)
      {
          var home = "http://myurl";
          var reportLink = {item};
          var link = home + reportLink.item;
          console.log(link);

          // HyperLink1.NavigateUrl = link;

          // return(<a href='"link"'>Report </a>);

          // return(<a href="'link'">Report </a>);

          // <a href="link" class='dynamicLink'>Report </a>;

          /*
          <div>
              <a  onclick="javascript:GoToUrl();"> Reports </a>
              <script type="text/javascript">
                  function GoToUrl()
                  {return("http://myurl" + {item});}
              </script>
          </div>
          */

          /*              
              <div>
                  <a onclick="return Try();"> Reports </a>
                  <script type="text/javascript">
                      function Try()
                      {return(link_final);}
                  </script>
              </div>              
          */

          return(<a href= "link">Report </a>);
      });
}

我需要做的是将变量“链接”传递给href。链接包含最终 URL。我已经尝试了一些我在上面的 cmets 中展示的解决方案。

基本上我想在第一个循环中传递“http://myurl+/reports/interactive/CustomersReport”,在第二个循环中传递“http://myurl+/reports/interactive/MapReport”。

请帮助我了解我可能在哪里出错。 谢谢!

【问题讨论】:

    标签: javascript html reactjs variables href


    【解决方案1】:

    如果你想使用ES6,我通常更喜欢这个,因为代码更简洁。

    import React from 'react';
    import { render } from 'react-dom';
    
    class App extends React.Component {
      constructor () {
        super()
        this.state = {
          repoLinks: ["/reports/interactive/CustomersReport",
                      "/reports/interactive/MapReport"]
        }
      }
      render () {
        var { repoLinks } = this.state
        var home = "http://myurl"
        repoLinks = repoLinks.map( (item,index) => {
          return `<a key=${index} href=${home}${item}>Link</a>`
        })
        return (<h1>{repoLinks}</h1>)
      }
    }
    render(<App />, document.getElementById('root'));
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      构建 URL 变量,然后将其传递给花括号中的 href,如下所示:

      return(<a href={link}>Report </a>);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-16
        • 2019-05-26
        • 2017-08-17
        • 2021-04-18
        • 1970-01-01
        • 2020-05-17
        • 2011-02-17
        • 2019-01-31
        相关资源
        最近更新 更多