ReactRouter-tutorial(196)

http://www.ruanyifeng.com/blog/2016/05/react_router.html?utm_source=tool.lu

  1. Router指定历史控件,切换路径历史直接:
1
2
import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
  1. Route来控制布局,path指定路径(path有匹配规则),component指定控件。
    <Link to="/about"> 被点击后,会激活to指定的相应路径,并渲染上面path指定的控件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/repos" component={Repos}>
<Route path="/repos/:repoName" component={Repo}/>
</Route>
<Route path="/about" component={About}/>
</Route>
</Router>
//上面App包含了俩个,可以通过分别激活路径来切换显示区
<Router history={hashHistory}>
<Route path="/" component={App}/>
<Route path="/repos" component={Repos}>
<Route path="/repos/:repoName" component={Repo}/>
</Route>
<Route path="/about" component={About}/>
</Router>
//三面三个同级,所以无论在哪个类里激活路径,都会跳转页面。
//注意如果在App里面激活`/repos/:repoName`,则会先激活`/repos`再来激活它的子组件
  1. <IndexRoute component={Home}/> 设置默认渲染组件,如放上面1 - App下面,就会成为默认children渲染。
    如果想在列表有个组件相应的选中项 还要在App加个 <li><NavLink to="/" onlyActiveOnIndex={true}>Home</NavLink></li>

  2. Contexts属性。

  • 通过context传递属性的方式可以大量减少 通过显式的通过 props 逐层传递属性的方式。这样可以减少组件之间的直接依赖关系
  • 如果你为一个组件指定了context,那么这个组件的子组件只要定义了contextTypes 属性,就可以访问到父组件指定的context了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var A = React.createClass({
contextTypes: {
name: React.PropTypes.string.isRequired,
},
render: function() {
return <div>My name is: {this.context.name}</div>;
}
});
React.withContext({'name': 'Jonas'}, function () {
// Outputs: "My name is: Jonas"
React.render(<A />, document.body);
});
/////////////////////////////////////////////////////////////////////////
//父类可以指定contextTypes,也可以指定childContextTypes;childContextTypes只是限定了传给子类的类型,无它就默认全下传。
var A = React.createClass({
childContextTypes: {
fruit: React.PropTypes.string.isRequired
},
getChildContext: function() {//如果不书写这个函数,子类则无法获取
return { fruit: "Banana",name: "Apple" };
},
render: function() {
return <B />;
}
});
var B = React.createClass({
contextTypes: {
name: React.PropTypes.string.isRequired,
fruit: React.PropTypes.string.isRequired
},
render: function() {
return <div>My name is: {this.context.name} and my favorite fruit is: {this.context.fruit}</div>;//由于父类限定了类型,所以如果是this.context.name就会报错
}
});
React.withContext({'name': 'Jonas'}, function () {//给A类,构造ContextTypes属性
React.render(<A />, document.body);
});
  1. 关于跳转的方式,一种是用相应的history来push,一种是用context.router来push

子类的contextTypes其实访问的是Routercontext,Router有个叫router的RouterContext类型变量

// //