2017-09-05 305 views
0

我有一个索引图像和标题,我从Dropbox API拉入。这些(点击时)已经创建并安装新组件。我试图将react-router整合到这个项目中,但我正在努力生成链接到=使用我已经创建的数组的路径。反应路由器:创建从对象创建'链接'路径

import { BrowserRouter, Route, Link } from 'react-router-dom' 

//titles variable created via api 
var titles=["title one","title two","title three",...] 


class Index extends React.Component{ 

    render(){ 
     if(!this.props.imageSource.length) 
      return null; 
      let titles = this.props.imageTitles.map((el, i) => <p>{el}</p>) 
      let images = this.props.imageSource.map((el, i) => 

       <div className="imageContainer"> 
        <img key={i} className='indexImages' src={el} onClick = {this.props.indexTitleClick.bind(this,titles[i])}/> 
        <Link to={titles[i]} className="imageTitle" onClick = {this.props.indexTitleClick.bind(this,titles[i])}>{titles[i]}</Link> 
       </div> 
      ) 



     return (
      <div className="indexWrapper"> 
       {images} 
      </div> 

     ); 
    } 
} 

正如你可以看到我试图用同样的方法,因为我有产生imageTitles,但href是简单的“/”渲染时。是否有可能以这种方式动态生成路径?

p.s.我试图保持代码简洁,但很高兴在需要时添加更多信息。

+0

'this.props.imageTitles'看起来像什么? –

+0

'titles [i]'should should'

title one

''我认为这不是一个有效的'to'支持。更改变量名称标题和titleshml或类似 – bennygenel

回答

2

不知道你是否知道这一点,但你重写titles

var titles=["title one","title two","title three",...] // from outside your component 
let titles = this.props.imageTitles.map((el, i) => <p>{el}</p>) // inside render 

然后,您试图链接到titles阵列的成员,但它持有该格式成员:

<p>{el}</p> 
+0

好点,OP如果你使用了一个const而不是var,你会很快捕获这个错误 – Nath

0

首先,你必须创建一个根类,你会宣布像一些路径下面的例子

<Router history={browserHistory} >    
    <Root path="/:pathVariable" component={ComponentClass}/>   
</Router> 

,然后用browserHistory.push( “/路径”)你将导航到http://host:port/path