1

所以我有一个钩子,它在更改时获取输入字段值并设置变量。

更新

HooksLib.js

 import { useState } from "react";

export function useFormFields(initialState) {
  const [fields, setValues] = useState(initialState);

  return [
    fields,
    function(e, name = '') {
      if (e instanceof Object && e.target instanceof Object) {
        // Safe to assume it was an event passed in
        setValues({ ...fields, [e.target.id]: e.target.value });
      } else {
        // Assume the value was passed in directly
        setValues({ ...fields, [name]: e });
      }
    }
  ];
}

我想使用相同的钩子在函数调用中设置一个变量。我该怎么做呢?

如何将 event.target.id 和 event.target.value 添加到函数调用中?

我想将其添加到的功能在下面....特别///then update a variable called "fields.customerId" as the value of "customer"是位于的位置。

handleSignUpSubmit 异步函数

const [fields, handleFieldChange] = useFormFields({
    name: "",
    email: "",
    customerId: "null"
  });

async function handleSignUpSubmit(event) {
    event.preventDefault();



    setIsLoading(true);

    try {
      const customer = await createCustomer({ email: fields.email, name: fields.name});
      ///then update a variable called "fields.customerId" as the value of "customer"
    } catch (e) {
      alert(e.message);
      setIsLoading(false);
    }
}

谢谢你的帮助!

4

1 回答 1

2

如果我正确理解您的问题,我会看到两个选项。

您可以制作一个类似于事件的对象并将其传入:

const myEvent = {
  target: {
    id: 'test',
    value: 'test2'
  }
}

...

handleFieldChange(myEvent);

或者另一种方法是在自定义钩子中包含一个检查,以允许使用键名作为可选参数传入事件或普通值:

function(e, name = '') {
  if (e instanceof Object && e.target instanceof Object) {
    // Safe to assume it was an event passed in
    setValues({ ...fields, [e.target.id]: e.target.value });
  } else {
    // Assume the value was passed in directly
    setValues({ ...fields, [name]: e });
  }
}

然后像这样调用它:

const customer = await createCustomer({ email: fields.email, name: fields.name});
handleFieldChange(customer, 'customerId');
于 2019-12-18T16:53:04.027 回答