LoginSignup
25
1

More than 5 years have passed since last update.

React「context API」を一筆書き。

Posted at

あらすじ

context APIとライフサイクル(componentDidMount)をあわせた、簡単な記事としてとりあえず書きたかった。
解説はまた別の機会にします。

注意点

この記事はReact 16.3以降で使える実装です。
React 16.2以前は、別の実装方法になり現在非推奨です。

実装

実用的というより、基本を抑えるイメージで書きました。

import React from "react";
import ReactDOM from "react-dom";
import { compose, withStateHandlers, lifecycle } from "recompose";
import "./styles.css";

const { Provider, Consumer } = React.createContext();

function App(props) {
  return (
    <Provider value={{ color: props.color }}>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <Consumer>
          {({ color }) => (
            <h2
              style={{
                backgroundColor: color
              }}
            >
              {color}
            </h2>
          )}
        </Consumer>
      </div>
    </Provider>
  );
}
const enhance = compose(
  withStateHandlers(
    {
      color: "red"
    },
    {
      handleColor: (state, props) => color => {
        return { color };
      }
    }
  ),
  lifecycle({
    componentDidMount() {
      const { handleColor } = this.props;

      setTimeout(() => {
        handleColor("blue");
      }, 1000);
    }
  })
);
const Main = enhance(props => <App {...props} />);

const rootElement = document.getElementById("root");
ReactDOM.render(<Main />, rootElement);
25
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
1