将值动态传递给href属性

时间:2017-06-20 17:55:40

标签: javascript html reactjs variables href

将下面的代码段粘贴为参考号:

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

我需要做的是传递变量&#39; link&#39;到href。链接包含最终的URL。我已经尝试了一些我在上面的评论中显示的解决方案。

基本上我想传递它&#34; http://myurl+/reports/interactive/CustomersReport&#34;在第一个循环和&#34; http://myurl+/reports/interactive/MapReport&#34;在第二个循环中。

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

2 个答案:

答案 0 :(得分: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'));

希望它会有所帮助。

答案 1 :(得分:0)

构建URL变量,然后使用大括号将其传递给href,如下所示:

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