index.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
// import React, { useState } from 'react' // const Context = React.createContext({ foo: 0, bar: 1 }, () => { }); const Context = React.createContext(); const Grandchild2 = () => { const e = React.createElement; return e(Context.Consumer, {}, value => { return e("div", {}, e("p", {}, `Grandchild2 ${value.values.bar}`), e("button", { onClick: () => value.setCount({ ...value.values, foo: value.values.foo + 100 }), }, "Click"), ); }); }; const Grandchild1 = () => { const e = React.createElement; const value = React.useContext(Context); // console.log(value); return e("p", {}, `Grandchild1 ${value.values.foo}`); }; const Child = () => { const e = React.createElement; return e("div", {}, [ e(Grandchild1, { key: 1 }), e(Grandchild2, { key: 2 }), ]); }; const App = () => { // console.log("App"); const e = React.createElement; // const Context = React.createContext(); const [values, setCount] = React.useState({ foo: 0, bar: 1 }); // console.log(values); // Similar to componentDidMount and componentDidUpdate: React.useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${values.foo} times`; }); return ( e(Context.Provider, { value: { values: values, setCount: setCount } }, e("p", {}, `Count: ${values.foo}, ${values.bar}`), e("button", { onClick: () => setCount({ foo: values.foo + 1, bar: values.bar + 1 }), }, "Click"), e(Child), ) ); }; // export default App |
index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hooks</title> <script src="./js/lib/react.development.js"></script> <script src="./js/lib/react-dom.development.js"></script> </head> <body> <div id="root"></div> <script src="./js/index.js"></script> <script> (function () { const e = React.createElement; ReactDOM.render(e(App), document.getElementById("root")); })(); </script> </body> </html> |
特に普通(?)だった。