hashHistory
什么用?
它控制着带着hash值的路由,比如说有两个路由
<Router history={hashHistory}>
<Route path="/" component={App}/>
{/* add the routes here */}
<Route path="/repos" component={Repos}/>
<Route path="/about" component={About}/>
</Router>
现在去访问的话通过hash值比如
localhost:8080/#/about
localhost:8080/#/repos
那我不想出现那个#呢?
那就用browserHistory
** Link 和 a 标签的区别**
其中一个区别是标记active。这个在导航的时候特别管用。
以往,想要标记active需要操作dom给导航添加class或者style。
Link
标签提供了两个接口 activeStyle
和 activeClassName
在Link
active的时候自动变换样式。
组件传参的技巧
以前在传参数的时候,总会在组件中定义一些东西,比如handleChange
、handleClick
啊什么的。甚至在拿数据的时候还传了handleRef
。
现在经过观看别人的项目,我发现几个更好的解决方案。
第一个,如何传一些onChange
什么的参数。很简单,{...this.props}
然后在父级的时候,传onChange()
。传什么就进来什么,每个组件的可定义度很高。
第二个,如何传input
中的数据,用event
,在onChange
事件中,可以传event
,然后通过event.target
来获取input
的DOM。so easy!
** 关于url中传参的问题**
比如,我想打开
/repos/reactjs/react-router
/repos/facebook/react
怎么整?
它其实在url中传了两个参数,我们暂且定义成这样
/repos/:userName/:repoName
第一、路由怎么写?
<Route path="/repos/:userName/:repoName" component={Repo}/>
第二、Link怎么写?
<Link to="/repos/reactjs/react-router">React Router</Link>
第三、如何在页面中取到参数?
<h2>{this.props.params.repoName}</h2>
这个其实还挺简单的。
关于用js来实现页面路由跳转问题
在react-router中,据我所知,有两种方法。
第一种,使用withRouter(),然后将在内部可以获取this.props.router。
第二种,使用this.context.router,不过在使用前必须定义这个类的contextTypes。
withRouter怎么用?
...
import {withRouter} from 'react-router'
class Abc extends Component {
...
this.props.router.push('/')
}
export default withRouter(Abc)
用context怎么用?
...
export default class Abc extends Component {
...
this.context.router.push('/')
}
Abc.contextTypes = {
router: React.PropsTypes.object
}
网友评论