第一种 childContextTypes
// 父组件
import React from 'react'
import PropTypes from 'prop-types'
import Test from './Test'
class Main extends React.Component {
state = {
a: 111111111
}
getChildContext() {
return {
a: this.state.a
}
}
render() {
return (
<Test />
)
}
}
Main.childContextTypes = {
a: PropTypes.number,
}
// 子组件
import React from 'react'
import PropTypes from 'prop-types'
class Test extends React.Component {
render() {
console.log(this.context.a)
return (
<div>TestTestTest</div>
)
}
}
Test.contextTypes = {
a: PropTypes.number
}
export default Test;
export default Main;
第二种 React.createContext(default,fn)
网友评论