简体   繁体   中英

passing values dynamically to href attribute

Pasting my snippet below as ref:

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>);
      });
}

What I need to do is to pass the variable 'link' to href. link contains the final URL. I have tried a few solutions that I have shown in comments above.

Basically I want to pass it " http://myurl+/reports/interactive/CustomersReport " in the first loop and " http://myurl+/reports/interactive/MapReport " in the 2nd loop.

Please help me understand where I could be going wrong here. Thanks!

If you want to go with ES6 , I usually prefer this because of cleaner code.

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'));

Hope it would help.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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