基本傳參props
傳遞數(shù)據(jù)
<child age={this.state.age}>
在子組件中
this.props.age獲取數(shù)據(jù)
傳方法
setAage = v =>this.setState({age:v})
<child age={this.state.age} setAge={this.setAge.bind(this)}>
在子組件使用
<h3 onClick={()=>this.props.setAge(15)}>
context
上下文傳遞參數(shù)
特點(diǎn):引入的context 數(shù)據(jù) 是時(shí)時(shí)更新? 當(dāng)一個(gè)數(shù)據(jù)發(fā)生改變所有引用數(shù)據(jù)的視圖都會(huì)自動(dòng)更新
父組件
1. 導(dǎo)入類型檢測(cè)
import PropTypes? from 'prop-types';
2. 定義導(dǎo)出的數(shù)據(jù)類型
? ? static childContextTypes = {
? ? ? ? color:PropTypes.string, // 字符串類型
? ? ? ? setColor:PropTypes.func,// 方法類型
? ? }
3.? 獲取需要傳參的數(shù)據(jù)
? ? getChildContext(){
? ? ? ? return {
? ? ? ? ? ? color:this.state.color,
? ? ? ? ? ? setColor:v=>this.setState({color:v})}
? ? }
子孫組件
1. 定義上下文數(shù)據(jù)類型
? ? static contextTypes = {
? ? ? ? color:PropTypes.string, // 字符串類型
? ? ? ? setColor:PropTypes.func,// 方法類型
? ? }
2. 使用上下文數(shù)據(jù)
<h3 style={{color:this.context.color}}>Child組件</h3>
使用上下文方法
<button onClick={()=>this.context.setColor('gold')}>
context
provider Comsumer
上下文方式傳遞
1. 定義 上下文組件
import React from 'react'
let { Consumer, Provider } = React.createContext();
// 創(chuàng)建一個(gè)上下文? 結(jié)構(gòu) Consumer 消費(fèi)者, Provider? 供應(yīng)商
export { Consumer, Provider }
// 導(dǎo)出
2. 父組件
1. 導(dǎo)入
import {Provider} from './context'
2. 用provider包裹子元素 并傳遞value數(shù)據(jù)
<Provider value={{
? ? ? ? ? ? ? ? num:this.state.num,
? ? ? ? ? ? ? ? setNum:this.setNum
? ? ? ? ? ? ? ? }}>
3. 子組件中
1. 導(dǎo)入
import { Consumer} from './context'
// 導(dǎo)入消費(fèi)者組件
2. Comsumer中的context 獲取數(shù)據(jù)
<Consumer>
? ? ? ? ? ? ? { context=>( <div> <h3> <button onClick={()=>context.setNum(context.num+1)}>{context.num}</button></h3> </div> ) }
</Consumer>
redux react-redux
全局?jǐn)?shù)據(jù)狀態(tài)共享
vuex就是有參考redux的
1 安裝? npm i redux react-redux
2. 從 react-redux導(dǎo)入Provider
import {Provider} from 'react-redux';
3. 把根組件替換為
<Provider>
? ? <App/>
</Provider>
4. 在Provider中添加數(shù)據(jù)倉庫
<Provider store={store}>
5. 編寫store倉庫并導(dǎo)入倉庫
6.編寫store
1. redux導(dǎo)入
2. reducer 初始數(shù)據(jù)方法
3. actions 處理數(shù)據(jù)動(dòng)作
4. 導(dǎo)出倉庫
7.在組件中使用
1.導(dǎo)入連接
2.導(dǎo)出組件
export default connect(mapStateToProps,mapDisPatchToProps)(Detail)
mapStateToProps 組state數(shù)據(jù)映射為 組件的props
mapDisPatchToProps 把state中的方法映射誒porps中的方法