组件实例的三大核心属性
1.state
2.props
3.refs
-
字符串形式的ref
<input ref="input1"/>
-
回调形式的ref
<input ref={c=>{this.input1=c}}/>
-
createRef创建ref容器
myRef=React.createRef() <input ref={this.myRef}/>
React生命周期(旧)
初始化
1、构造器
constructor(props){}
2、组件将要挂载
componentWillMount(){}
3、render
render(){}
4、组件挂载完毕
componentDidmount(){}
卸载组件方法
ReactDOM.unmountComponentAtNode(document.getElementById(''))
5、组件将要卸载
componentWillUnmount(){}
更新
(父组件render)
1、组件props将要更新
componentWillReceiveProps(props){}
(this.setState()或父组件render)
2、是否更新组件
shouldComponentUpdate(){
reutrn <Boolean>
}
(this.setState()或父组件render或强制更新this.forceUpdate())
3、组件将要更新
componentWillUpdate(){}
4、render()
5、组件更新完毕
componentDidUpdate(){}
卸载
1、组件将要卸载
componentWillUnmount(){}
React生命周期(新)
初始化
由ReactDOM.render()触发——初次渲染
1、constructor()
2、getDerivedStateFromProps
从props获取派生状态,当state的值在任何时候都取决于props时,可以使用
3、render()
4、componentDidMount()
组件挂载完毕
更新
由组件内部this.setState()、this.forceUpdate或父组件重新render触发
1、getDerivedStateFromProps
2、shouldComponentUpdate()
组件是否更新(this.forceUpdate()将会跳过此过程)
3、render()
4、getSnapshotBeforeUpdate()
更新前获取快照
5、componentDidUpdate()
组件更新完毕
卸载
由ReactDOM.unmountComponentAtNode()触发
1、componentwillUnmount()
父子组件传值
父传子
-
在父组件中使用子组件时,为其传递属性值
render(){ return ( <div> <Header title={this.status.title}/> </div> ) }
-
在子组件中接收父组件传递过来的属性
//使用 {this.props.propsName} 的方式接收属性 render(){ return ( <div> <h1>{this.props.title}</h1> </div> ) }
**注意:**当你遇到需要同时获取多个子组件数据,或者两个组件之间需要相互通讯的情况时,需要把子组件的 state 数据提升至其共同的父组件当中保存。之后父组件可以通过 props 将状态数据传递到子组件当中。这样应用当中所有组件的状态数据就能够更方便地同步共享了。
路由
-
导航区 通过
Link
标签创建路由链接<Link to="/about">About</Link>
-
展示区通过
Route
标签进行路由匹配import About from './components/about' <Route path="/about" component={About} />
-
使用
BrowserRouter
或HashRouter
将所有路由包裹起来<BrowserRouter><App/></BrowserRouter>
一般组件与路由组件的区别
-
写法不同
//一般组件: <Header/> //路由组件: <Router path="/about" component={About} />
-
存放的位置不同
一般组件:components
路由组件:pages
-
收到的props不同
一般组件:给组件传递什么,就收到什么
路由组件:收到三个固定的属性
history: go: ƒ go(n) goBack: ƒ goBack() goForward: ƒ goForward() push: ƒ push(path, state) replace: ƒ replace(path, state) location: pathname: "/about" search: "" state: undefined match: isExact: true params: {} path: "/about" url: "/about"
路由标签
Link
创建路由链接
<Link to="/about">About</Link>
NavLink
创建路由链接,通过指定activeClassName
,为点击后的导航添加相应类名
<NavLink activeClassName="activeNav" className="list-group-item" to="/about">About</NavLink>
Switch
- 通常情况下,path和component是一一对应的关系
- Switch可以提高路由的匹配效率(单一匹配)
<Switch>
<Route path="/about" component={About} />
<Route path="/home" component={Home} /> //此时只会显示Home组件,不会继续向后匹配路由
<Route path="/home" component={Test} />
</Switch>
路由严格匹配
//默认模糊匹配 Link链接的路径必须包含Route匹配的路径,且顺序要一致
<Link to="/home/a/b">Home</Link>
<Route path="/home" component={Home} /> //此时home可以被匹配到
//开启严格匹配 exact={true} 简写exact
<Link to="/home/a/b">Home</Link>
<Route exact path="/home" component={Home} /> //此时home无法被匹配到
严格匹配不要随便开启,需要时再开,有些时候开启会导致无法匹配