Movatterモバイル変換


[0]ホーム

URL:


ReasonReact

ReasonReact

Edit

Context

In order to use React's context, you need to create two things:

  1. The context itself
  2. A context provider component
/** as a separate file: ContextProvider.re *///1.The context itselflet themeContext =React.createContext("light");//2.The providerincludeReact.Context;//Adds the makePropsexternallet make =React.Context.provider(themeContext);
/** or inside any other module *///1.The context itselflet themeContext =React.createContext("light");//2.The provider componentmoduleContextProvider = {includeReact.Context;//Adds the makePropsexternallet make =React.Context.provider(themeContext);};

That will give you aContextProvider component you can use in your application later on, by wrapping any component withContextProvider, to have access to the context value inside the component tree. To know more about Context, check thecreateContext page of the React.js documentation andwhen to use it.

/** App.re */[@react.component]let make = () =>  <div>    <ContextProvider value="light">      <ComponentToConsumeTheContext />    </ContextProvider>  </div>

Then you can consume the context by using theReact.useContext hook

/** ComponentToConsumeTheContext.re */[@react.component]let make = () => {let theme =React.useContext(ContextProvider.themeContext);  <h1>theme->React.string</h1>}

Binding to an external Context

Binding to a Context defined in a JavaScript file holds no surprises.

/** ComponentThatDefinesTheContext.js */exportconst ThemeContext = React.createContext("light");
/** ComponentToConsumeTheContext.re */[@bs.module "ComponentThatDefinesTheContext"]external themeContext:React.Context.t(string) ="ThemeContext";[@react.component]let make = () => {let theme =React.useContext(themeContext);  <h1>theme->React.string</h1>}
Ternary ShortcutNext

[8]ページ先頭

©2009-2025 Movatter.jp