当我们使用父组件向子组件传值的时候我们可以用context
1.props-type 这是16之前的版本
他的缺点是:当父组件context发生改变,子组件必须全部改变,无论你有没有使用,所以性能方面比较差
使用方法
parent.js
import React,{Component,createContext} from 'react';
import { Button } from 'antd';
import PropTypes from 'prop-types'
import Child from './component/child'
interface Iprops{
history?:any
}
interface Istate{
name:string,
age:string
}
const { Provider } = createContext('light')
class parent extends Component<Iprops,Istate>{
constructor(props:Iprops){
super(props)
this.state = {
name:'隔壁老王',
age:'100'
}
}
// 在父组件中 定义上下文类型
static childContextTypes = {
}
// 在父组件中 给context填充数据
getChildContext() {
return { // 返回context对象
users: this.getUsers(),
userMap: this.getUserMap()
}
}
getUsers = () => {
return '12344'
// ... 获取数据
}
getUserMap = () => {
return '哈哈哈哈哈哈'
// ... 获取数据
}
public getClicks=()=>{
this.props.history.push({pathname:'/admin/home',query:{name:'大boss'}})
}
public render(){
return (
<div>
<Button onClick={this.getClicks}>点击</Button>
</div>
)
}
}
UserConnect.childContextTypes={
users: PropTypes.string,
userMap: PropTypes.string
}//这个一定要写不然报错
export default UserConnect
child.js
import React ,{Component,createContext} from 'react'
import PropTypes from 'prop-types'
class Child2 extends Component{
static contextTypes = {
}
public render(){
return (
<div>
{this.context.userMap}
</div>
)
}
}
Child2.contextTypes={
userMap: PropTypes.string
}
export default Child2
2.createContext()
他的好处就是当父组件的发生改变时 只有使用的子组件重新渲染
使用方法
parent.js
import React,{Component,createContext} from 'react';
import { Button } from 'antd';
import PropTypes from 'prop-types'
import Child from './component/child'
import wrapContext from './component/userContext'
interface Iprops{
history?:any
}
interface Istate{
name:string,
age:string
}
class Parent extends Component<Iprops,Istate>{
constructor(props:Iprops){
super(props)
this.state = {
name:'隔壁老王',
age:'100'
}
}
// 在父组件中 定义上下文类型
static childContextTypes = {
}
public getClicks=()=>{
this.props.history.push({pathname:'/admin/home',query:{name:'大boss'}})
}
public render(){
return (
<div>
<Button onClick={this.getClicks}>点击</Button>
<div>
<wrapContext.Provider value={{'name':this.state.name,'age':this.state.age}}>
<Child/>
</wrapContext.Provider>
</div>
</div>
)
}
}
export default Parent
child.js
import React ,{Component,createContext} from 'react'
import wrapContext from './userContext'
class Child2 extends Component{
static contextTypes = {
}
public render(){
return (
<div>
{this.context.userMap}
<wrapContext.Consumer >
{value=><span>{value.name}</span>}
</wrapContext.Consumer>
</div>
)
}
}
Child2.contextTypes={
userMap: PropTypes.string
}
export default Child2
userContext
import {createContext} from 'react'
const userContext = createContext({name:'',age:''})
export default userContext