首页 > 其他分享 >[React] React hook, component props for refactoring

[React] React hook, component props for refactoring

时间:2023-02-19 03:33:12浏览次数:38  
标签:index const component value React hook send type event

Idea is put component props inside hook, and return from hook, that's way to keep component clean and simple

 

Hook:

import { MachineOptions } from "./machine";
import { machine } from "./machine";
import { useMachine } from "@zag-js/react";
import { ComponentProps } from "react";

type LabelProps = ComponentProps<"label"> & { "data-part": "label" };
type InputProps = ComponentProps<"input"> & {
  "data-part": string;
};

export function usePinMachine(options: MachineOptions) {
  const [state, send] = useMachine(machine(options));
  const { value, name } = state.context;
  const valueAsString = value.join("");
  return {
    value,
    valueAsString,
    getLabelProps(): LabelProps {
      return {
        "data-part": "label",
        onClick() {
          send({ type: "LABEL_CLICK" });
        },
      };
    },
    getHiddenInput(): InputProps {
      return {
        "data-part": "hidden-input",
        type: "hidden",
        name,
        value: value.join(""),
      };
    },
    getInputProps({ index }: { index: number }): InputProps {
      return {
        "data-part": "input",
        value: value[index],
        maxLength: 2,
        onChange(event) {
          const { value } = event.target;
          send({ type: "INPUT", index, value });
        },
        onFocus() {
          send({ type: "FOCUS", index });
        },
        onBlur() {
          send({ type: "BLUR" });
        },
        onKeyDown(event) {
          const { key } = event;
          if (key === "Backspace") {
            send({ type: "BACKSPACE", index });
          }
        },
        onPaste(event) {
          event.preventDefault();
          const value = event.clipboardData.getData("Text").trim();
          send({ type: "PASTE", value, index });
        },
      };
    },
  };
}

 

Component:

import "./App.css";
import { usePinMachine } from "./use-pin-machine";

function App() {
  const { value, getLabelProps, getHiddenInput, getInputProps } = usePinMachine(
    {
      numOfFields: 4,
      name: "pincode",
      onCompleted(value) {
        console.log(value);
      },
    }
  );

  return (
    <div className="App">
      <form
        onSubmit={(event) => {
          event.preventDefault();
          const formData = new FormData(event.currentTarget);
        }}
      >
        <div data-part="container">
          <label {...getLabelProps()}>Enter verification</label>
          <input {...getHiddenInput()} />
          <div data-part="input-group">
            {value.map((_, index) => (
              <input key={index} {...getInputProps({ index })} />
            ))}
          </div>
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default App;

 

标签:index,const,component,value,React,hook,send,type,event
From: https://www.cnblogs.com/Answer1215/p/17134148.html

相关文章

  • react中Hooks的理解和用法
    一、Hooks是什么?Hook 是React16.8的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性至于为什么引入hook,官方给出的动机是解决......
  • 【Android逆向】frida hook so 函数
    1.apk来自52pojie链接:https://pan.baidu.com/s/1vKC1SevvHfeI7f0d2c6IqQ密码:u1an2.apktool反编译apk,拿到so文件java-jar../apktool_2.2.4.jardapp-debug.apk3.......
  • reactor rabbitmq 实现RPC远程调用
    照着官方文档上写,最后发现在消费端怎么也返回不了数据。在文档中也找不到怎么返回数据,查看官方demo也没有案例,各种搜索都找不到。最后在源码中发现有一个RpcServer类,经过......
  • #yyds干货盘点 react笔记之学习之state组件
    前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从......
  • #yyds干货盘点 react笔记之学习之state注意事项
    前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从......
  • react项目搭建
    前提:安装Nodejs环境 #全局安装脚手架npmicreate-react-app-g#project-name项目名称create-react-appproject-name方式二:使用npx替代npm 推荐使用......
  • react知识点汇总
    一、react认识用于构建用户界面的JavaScript库二、创建react项目:react脚手架创建react项目,创建新的react应用npxcreate-react-appmy-appcdmy-appnpm......
  • react-事件绑定this的指向
    三种方式:     ......
  • vue2 vue-router.esm.js:16 [vue-router] Failed to resolve async component default
    敢信,晚上加班找这个错误,TMD找了二小时,网上各种百度。。。。。。原因竟然是这个ProductCategory组件,没有import进来,而components中却引用了!!!!低级错误,粗心问题!!!这也再次证......
  • #yyds干货盘点 react笔记之学习之显示日期
    前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五年的时间超越他今天又是接近兄弟的一天人生难免坎坷大不了从......