Context特性
若组件多层包裹 且外层属性或方法要传递给内层的组件 则传递会变得比较麻烦
比如:
import React from 'react';
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
mycolor:"red"
}
}
render() {
return <div>
<h1>I'm Parent</h1>
<Son mycolor={this.state.mycolor}></Son>
</div>
}
}
class Son extends React.Component {
render() {
return <div>
<h3>I'm Son</h3>
<Grandson mycolor={this.props.mycolor}></Grandson>
</div>
}
}
class Grandson extends React.Component {
render() {
return <div>
<h5 style={{color:this.props.mycolor}}>I'm Grandson</h5>
</div>
}
}
此时 可以使用Context特性
在父组件上直接共享一个Context对象 然后内层的组件无需逐层传递数据了 想要使用 直接从Context获取即可
在想要共享属性或方法的父组件里提供一个getChildContext()
方法(方法名不能改变)
在里面返回一个对象 该对象即为要共享给所有子孙组件的数据
然后使用childContextTypes
属性进行属性校验
在要使用数据的子组件里使用contextTypes
属性进行属性校验 然后用this.context.属性名
获取属性即可
像这样:
import React from 'react';
import ReactPropTypes from 'prop-types' // 属性校验包
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
mycolor:"red"
}
}
// 在父组件中定义一个function 固定名称getChildContext 且内部必须返回一个对象
// 该对象即为要共享给所有子孙组件的数据
getChildContext()
{
return {
mycolor:this.state.mycolor
}
}
// 属性校验 规定传给子孙组件的数据类型
static childContextTypes={
mycolor:ReactPropTypes.string
}
render() {
return <div>
<h1>I'm Parent</h1>
<Son></Son>
</div>
}
}
class Son extends React.Component {
render() {
return <div>
<h3>I'm Son</h3>
<Grandson></Grandson>
</div>
}
}
class Grandson extends React.Component {
// 属性校验 校验从父组件传来的数据类型
static contextTypes={
mycolor:ReactPropTypes.string // 若子组件要使用父组件通过Context共享的数据 那么在使用前一定要进行数据校验
}
render() {
return <div>
<h5 style={{color:this.context.mycolor}}>I'm Grandson</h5>
</div>
}
}
当然 Context使用的前提是必须为父子关系组件 若是平级的组件 则无此特性