Skip to content

zhengjiaqi/use-bind

Repository files navigation

use-bind

Responsive two-way binding between components

NPM JavaScript Style Guide

中文版-组件间响应式双向绑定

Install

npm install --save use-bind

Usage

Live Code

import * as React from 'react';

import useBind from 'use-bind';

const useBindExample = () => {
  const myBind = useBind(true);

  const onClick = useCallback(() => {
    myBind.value = myBind.value + 1
  }, [myBind])

  return (
    <div>
      <p onClick={onClick}>
          Click me and value will increment to {myBind.value} .
      </p>
    </div>
  );
};
};

Examples

Using it between components

Live Demo Code

Live Demo Example

Source code - ParentComponentExample.tsx

// ParentComponentExample.tsx
const ParentComponent: React.FC<IParentComponent> = (props: IParentComponent) => {
  const myBind = useBind(1);
  const onClick = useCallback(() => {
    myBind.value += 10;
  }, [myBind]);

  return (
    <div>
      <div className="parent-componment-value-click" onClick={onClick}>
        <span>Click me</span> will increase the value of the child component by 10 each time.
      </div>
      <ChildComponent myBind={myBind}></ChildComponent>
    </div>
  );
}

Source code - ChildComponentExample.tsx

// ChildComponentExample.tsx
interface IChildComponent {
  myBind: IBind<number>
}

const ChildComponent: React.FC<IChildComponent> = ({ myBind }: IChildComponent) => {
  const onClick = useCallback(() => {
    myBind.value += 1;
  }, [myBind]);

  return (
    <div>
      <div className="child-componment-value-click" onClick={onClick}>
        <span>Click me</span> will increase the value of the child component itself by 1 each time.
      </div>
      <div className="child-componment-value">
       Child Component Value: <span>{myBind.value}</span>
      </div>
    </div>
  );
}

License

MIT © zhengjiaqi


This hook is created using create-react-hook.

About

React 组件间响应式双向绑定hook

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published