react-observed-context
    TypeScript icon, indicating that this package has built-in type declarations

    2.0.0 • Public • Published

    react-observed-context

    利用React隐藏特性来让Context只在当前组件使用字段改变时更新组件。

    使用

    yarn add react-observed-context

    示例

    import { render } from "react-dom";
    
    import createObservedContext from "react-observed-context";
    
    
    const Context = createObservedContext({ user: "", password: "" });
    
    const Input = ({ name }) => {
      const [ state, setState ]= Context.useObservedState(name);
      return (
        <input
          type="text"
          value={state[name]}
          onChange={({ target }) =>
            setState((prev) => ({ ...prev, [name]: target.value }))
          }
        />
      );
    };
    
    function App() {
      return (
        <Context.Provider>
          <Input name="user" />
          <Input name="password" />
        </Context.Provider>
      );
    }
    
    render(<App />, document.getElementById("root"));

    API

    createObservedContext

    /**
     * baseState 默认值
     */
    function createObservedContext(baseState)

    <Context.Provider />

    <Context.Provider>
      { children... }
    </Context.Provider>

    Context.useObservedState

    /**
     * key 观察的字段,数组或字符串,false为不观察,如自定义第二个setState
     */
    function useObservedState(key)

    警告

    此功能依赖React非稳定性future,开发环境控制台会有warning警告。

    最多可观察31个字段。

    Keywords

    none

    Install

    npm i react-observed-context

    DownloadsWeekly Downloads

    1

    Version

    2.0.0

    License

    MIT

    Unpacked Size

    7.87 kB

    Total Files

    7

    Last publish

    Collaborators

    • zhangyu1995