From aec8c8ac7a3b0314c9c3690fa2dedf0b30e12cc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A5=87=E8=B6=A3=E4=BF=9D=E7=BD=97?= Date: Thu, 25 Apr 2024 11:32:52 +0800 Subject: [PATCH] Update useForm hooks supports input type checkbox MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持 checkbox,虽然只是返回 boolean,但这个判断和正常表单还是有区别的 --- contents/read.ts | 9 --------- hooks/useForm.ts | 35 +++++++++++++++++++++++++++++------ 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/contents/read.ts b/contents/read.ts index 171a96f..ce95db7 100644 --- a/contents/read.ts +++ b/contents/read.ts @@ -46,14 +46,6 @@ const getDesc = () => { return ""; } -const getFrom = () => { - if (location.host === "mp.weixin.qq.com") { - return "wechat"; - } - - return "web"; -} - const getAuthor = () => { const metaAuthor = document.querySelector(`meta[name="author"]`); const metaOgAuthor = document.querySelector(`meta[property="og:article:author"]`); @@ -128,7 +120,6 @@ chrome.runtime.onMessage.addListener((req, sender, send) => { title: getTitle(), link: `${location.origin}${location.pathname}`, desc: getDesc(), - from: getFrom(), author: getAuthor(), image: getImage(), sitename: getSiteName(), diff --git a/hooks/useForm.ts b/hooks/useForm.ts index 015651d..e4b65b6 100644 --- a/hooks/useForm.ts +++ b/hooks/useForm.ts @@ -21,6 +21,10 @@ interface UseFormReturns { onSubmit: (fn: (values: T) => void) => (ev: React.FormEvent) => void } +const isCheckBox = (el: HTMLElement) => { + return el instanceof HTMLInputElement && el.type === "checkbox"; +} + function useForm({ initialValues }: Props) { const inputs = useRef>>({}); const values = useRef({ ...initialValues } as T); @@ -32,10 +36,19 @@ function useForm({ initialValues }: Props) { } const setValue = (name, value) => { - console.log(inputs.current[name], name); + const el = inputs.current[name]; - if (inputs.current[name]) { + console.log(el, name); + + if (el) { values.current[name as keyof T] = value; + + if (el instanceof HTMLInputElement && el.type === "checkbox") { + el.checked = value; + + return; + } + inputs.current[name].value = value; } } @@ -47,8 +60,6 @@ function useForm({ initialValues }: Props) { } const bindInput = (name: string) => { - console.log('bindinput') - return { name, id: name, @@ -57,11 +68,23 @@ function useForm({ initialValues }: Props) { if (target) { inputs.current[name as keyof T] = target; + + if (isCheckBox(target)) { + target.checked = initialValues?.[name]; + } + else if (name in initialValues) { + target.value = initialValues[name]; + } } }, - defaultValue: initialValues[name], onChange: (ev) => { - const { name, value } = ev.target; + const { name, value, checked } = ev.target; + + if (isCheckBox(ev.target)) { + values.current[name as keyof T] = checked; + + return; + } values.current[name as keyof T] = value; },