reactのcontextの使い方
1839 ワード
まずcontextを使う時はget ChildConttextを使いましょう.this.state returnが出てきます.属性は を検証しなければならない.
以下はすべてのコードの親コンポーネントです.
getChildContext = () => {
return {
themeColor: this.state.themeColor,
onMainClick: this.state.onMainClick
}
}
そしてstatic child Contect Typesを使って属性を検証します.static childContextTypes = {
themeColor: PropTypes.string,
onMainClick: PropTypes.func
}
サブコンポーネントの中でこれはもう一回検証して使えます. static contextTypes = {
themeColor: PropTypes.string,
onMainClick: PropTypes.func
}
サブコンポーネントの使い方
main-content
{this.context.themeColor}
サブアセンブリでの使い方も同じです.以下はすべてのコードの親コンポーネントです.
import React,{Component} from 'react';
import PropTypes from 'prop-types'
class Header extends Component {
constructor(props){
super(props);
this.state = {};
}
render() {
const {themeColor} = this.props
return (
header
{themeColor}
);
}
}
Header.propTypes = {
themeColor: PropTypes.string
}
export default Header
サブコンポーネントimport React,{Component} from 'react';
import PropTypes from 'prop-types'
class Main extends Component {
static contextTypes = {
themeColor: PropTypes.string,
onMainClick: PropTypes.func
}
constructor(props){
super(props);
this.state = {};
}
render() {
return (
main-content
{this.context.themeColor}
);
}
}
export default Main