Reactjs 如何在react hook表单中设置Select的值?

Reactjs 如何在react hook表单中设置Select的值?,reactjs,material-ui,react-hook-form,Reactjs,Material Ui,React Hook Form,我正在尝试加载异步数据,并使用它在带有react hook表单的表单中填充材质ui组件。我有一个TextField似乎工作正常,但我似乎不知道如何让Select显示正确的值 这里有一个演示我的问题 我正在使用控制器来管理选择,就像文档中建议的那样: const { register, handleSubmit, control, reset, setValue } = useForm() <TextField name="name" inputRef={reg

我正在尝试加载异步数据,并使用它在带有react hook表单的表单中填充材质ui组件。我有一个
TextField
似乎工作正常,但我似乎不知道如何让
Select
显示正确的值

这里有一个演示我的问题

我正在使用
控制器
来管理
选择
,就像文档中建议的那样:

  const { register, handleSubmit, control, reset, setValue } = useForm()

  <TextField name="name" inputRef={register} />
  <Controller
    name="color_id"
    control={control}
    register={register}
    setValue={setValue}
    as={
      <Select>
        {thingColors.map((tc, index) => (
          <MenuItem key={index} value={tc.id}>
            {tc.name}
          </MenuItem>
        ))}
      </Select>
    }
  />
这似乎正确地设置了表单的值,当我提交表单时,它似乎具有
name
color\u id
的正确值。似乎我没有正确连接
Select
,控件也没有显示我设置的选定值


如何获取我的材料界面
选择
以在此处显示我的应用值?

您好,您可以执行以下操作:

const Form: FC = () => {
  const { register, handleSubmit, control, reset, setValue } = useForm();
const [color, setColor] = useState({name:"", color_id:-1})
  useEffect(() => {
    getData().then((result) => {
      console.log("Got thing data", { result });
      reset({
        color_id: result.optionId,
        name: result.name
      });
      setColor( {color_id: result.optionId,
        name: result.name});
    });
  }, [reset]);

  const onSubmit = (data: any) => console.log("Form submit:", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div style={{ width: "200px" }}>
        <div>
          <TextField
            fullWidth
            name="name"
            placeholder="Name"
            inputRef={register}
          />
        </div>
        <div>
          <Controller
            name="color_id"
            control={control}
            register={register}
            setValue={setValue}
            defaultValue={color.name}
            as={
              <Select value="name" name="color_id" fullWidth>
                {thingColors.map((tc, index) => (
                  <MenuItem key={index} value={tc.id}>
                    {tc.name}
                  </MenuItem>
                ))}
              </Select>
            }
          />
        </div>
        <p></p>
        <button type="submit">Submit</button>
      </div>
    </form>
  );
};
<Button
   handler={handleSubmit(handlerSignInButton)}
   disable={!isValid || isSubmitting}
   label={"Guardar"}
 />
const Form:FC=()=>{
const{register,handleSubmit,control,reset,setValue}=useForm();
const[color,setColor]=useState({name:,color\u id:-1})
useffect(()=>{
getData()。然后((结果)=>{
log(“gotthingdata”,{result});
重置({
颜色id:result.optionId,
名称:result.name
});
setColor({color\u id:result.optionId,
名称:result.name});
});
},[reset]);
const onSubmit=(数据:any)=>console.log(“表单提交:”,数据);
返回(
(
{tc.name}
))}
}
/>

提交 ); };

您可以使用
useState()
来控制使用
getData()
方法获取的默认值,然后将状态传递给
控制器中的
defaultValue
参数

const Form: FC = () => {
  const { register, handleSubmit, control, reset, setValue } = useForm();
const [color, setColor] = useState({name:"", color_id:-1})
  useEffect(() => {
    getData().then((result) => {
      console.log("Got thing data", { result });
      reset({
        color_id: result.optionId,
        name: result.name
      });
      setColor( {color_id: result.optionId,
        name: result.name});
    });
  }, [reset]);

  const onSubmit = (data: any) => console.log("Form submit:", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div style={{ width: "200px" }}>
        <div>
          <TextField
            fullWidth
            name="name"
            placeholder="Name"
            inputRef={register}
          />
        </div>
        <div>
          <Controller
            name="color_id"
            control={control}
            register={register}
            setValue={setValue}
            defaultValue={color.name}
            as={
              <Select value="name" name="color_id" fullWidth>
                {thingColors.map((tc, index) => (
                  <MenuItem key={index} value={tc.id}>
                    {tc.name}
                  </MenuItem>
                ))}
              </Select>
            }
          />
        </div>
        <p></p>
        <button type="submit">Submit</button>
      </div>
    </form>
  );
};
<Button
   handler={handleSubmit(handlerSignInButton)}
   disable={!isValid || isSubmitting}
   label={"Guardar"}
 />
const Form:FC=()=>{
const{register,handleSubmit,control,reset,setValue}=useForm();
const[color,setColor]=useState({name:,color\u id:-1})
useffect(()=>{
getData()。然后((结果)=>{
log(“gotthingdata”,{result});
重置({
颜色id:result.optionId,
名称:result.name
});
setColor({color\u id:result.optionId,
名称:result.name});
});
},[reset]);
const onSubmit=(数据:any)=>console.log(“表单提交:”,数据);
返回(
(
{tc.name}
))}
}
/>

提交 ); };

您可以使用
useState()
来控制使用
getData()
方法获取的默认值,然后将状态传递给
Controller
中的
defaultValue
参数。在react hook表单的第7版中,您可以使用setValue()

注意:我使用shouldValidate,这是因为我在按钮中使用isValidate,如下所示:

const Form: FC = () => {
  const { register, handleSubmit, control, reset, setValue } = useForm();
const [color, setColor] = useState({name:"", color_id:-1})
  useEffect(() => {
    getData().then((result) => {
      console.log("Got thing data", { result });
      reset({
        color_id: result.optionId,
        name: result.name
      });
      setColor( {color_id: result.optionId,
        name: result.name});
    });
  }, [reset]);

  const onSubmit = (data: any) => console.log("Form submit:", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div style={{ width: "200px" }}>
        <div>
          <TextField
            fullWidth
            name="name"
            placeholder="Name"
            inputRef={register}
          />
        </div>
        <div>
          <Controller
            name="color_id"
            control={control}
            register={register}
            setValue={setValue}
            defaultValue={color.name}
            as={
              <Select value="name" name="color_id" fullWidth>
                {thingColors.map((tc, index) => (
                  <MenuItem key={index} value={tc.id}>
                    {tc.name}
                  </MenuItem>
                ))}
              </Select>
            }
          />
        </div>
        <p></p>
        <button type="submit">Submit</button>
      </div>
    </form>
  );
};
<Button
   handler={handleSubmit(handlerSignInButton)}
   disable={!isValid || isSubmitting}
   label={"Guardar"}
 />
我还没有使用过带有react-hook表单的材质UI,但希望这对您有所帮助

我的选择组件的示例,在Ionic React Typescript中:

import { ErrorMessage } from "@hookform/error-message";
import { IonItem, IonLabel, IonSelect, IonSelectOption } from 
"@ionic/react";
import { FunctionComponent } from "react";
import { Controller } from "react-hook-form";

type Opcion = {
  label: string;
  value: string;
};

interface Props {
  control: any;
  errors: any;
  defaultValue: any;
  name: string;
  label: string;
  opciones: Opcion[];
}

const Select: FunctionComponent<Props> = ({
  opciones,
  control,
  errors,
  defaultValue,
  name,
  label
  }) => {
    return (
      <>
        <IonItem className="mb-4">
          <IonLabel position="floating" color="primary">
            {label}
        </IonLabel>
        <Controller
          render={({ field: { onChange, value } }) => (
            <IonSelect
              value={value}
              onIonChange={onChange}
              interface="action-sheet"
              className="mt-2"
            >
                {opciones.map((opcion) => {
                   return (
                     <IonSelectOption value={opcion.value}
                       key={opcion.value}
                     >
                       {opcion.label}
                     </IonSelectOption>
                   );
                })}
            </IonSelect>
          )}
          control={control}
          name={name}
          defaultValue={defaultValue}
          rules={{
            required: "Este campo es obligatorio",
          }}
      />
    </IonItem>
      <ErrorMessage
        errors={errors}
        name={name}
        as={<div className="text-red-600 px-6" />}
      />
    </>
  );
};

export default Select;
从“@hookform/error message”导入{ErrorMessage};
从导入{IonItem、IonLabel、IonSelect、IonSelectOption}
“@离子/反应”;
从“react”导入{FunctionComponent};
从“react hook form”导入{Controller};
类型Opcion={
标签:字符串;
值:字符串;
};
界面道具{
对照组:任何;
错误:任何;
默认值:任意;
名称:字符串;
标签:字符串;
opciones:Opcion[];
}
常量选择:函数组件=({
选项,
控制
错误,
默认值,
名称
标签
}) => {
返回(
{label}
(
{opciones.map((opcion)=>{
返回(
{opcion.label}
);
})}
)}
control={control}
name={name}
defaultValue={defaultValue}
规则={{
必填:“Este campo es obligatio”,
}}
/>
);
};
导出默认选择;
及其实施:

import React, { useEffect } from "react";
import Select from "components/Select/Select";
import { useForm } from "react-hook-form";
import Server from "server";

interface IData {
  age: String;
}

let defaultValues = {
  age: ""
}

const rulesEdad= {
  required: "Este campo es obligatorio",
}

const opcionesEdad = [
  {value: "1", label: "18-30"},
  {value: "2", label: "30-40"},
  {value: "3", label: "40-50"},
  {value: "4", label: "50+"}
]

const SelectExample: React.FC = () => {

const {
  control,
  handleSubmit,
  setValue,
  formState: { isSubmitting, isValid, errors },
} = useForm<IData>({
  defaultValues: defaultValues,
  mode: "onChange",
});

/**
 *
 * @param data
*/
const handlerButton = async (data: IData) => {
  console.log(data);
};

useEffect(() => {
 Server.getUserData()
  .then((response) => {
    setValue('age', response.age, { shouldValidate: true })
  }
}, [])

return (
  <form>
    <Select control={control} errors={errors}
      defaultValue={defaultValues.age} opciones={opcionesEdad}
      name={age} label={Edad} rules={rulesEdad}
    />
    <button
        onClick={handleSubmit(handlerSignInButton)}
        disable={!isValid || isSubmitting}
    >
      Guardar
    </button>
  </form>
import React,{useffect}来自“React”;
从“组件/选择/选择”导入选择;
从“react hook form”导入{useForm};
从“服务器”导入服务器;
界面IData{
年龄:弦;
}
设默认值={
年龄:“
}
常量规则sedad={
必填:“Este campo es obligatio”,
}
const opcionesEdad=[
{值:“1”,标签:“18-30”},
{值:“2”,标签:“30-40”},
{值:“3”,标签:“40-50”},
{值:“4”,标签:“50+”}
]
const SelectExample:React.FC=()=>{
常数{
控制
手推,
设置值,
formState:{isSubmitting,isValid,errors},
}=使用形式({
defaultValues:defaultValues,
模式:“onChange”,
});
/**
*
*@param数据
*/
常量handlerButton=async(数据:IData)=>{
控制台日志(数据);
};
useffect(()=>{
Server.getUserData()
。然后((响应)=>{
setValue('age',response.age,{shouldValidate:true})
}
}, [])
返回(
瓜达尔

在react hook表单的第7版中,您可以使用setValue()

注意:我使用shouldValidate,这是因为我在按钮中使用isValidate,如下所示:

const Form: FC = () => {
  const { register, handleSubmit, control, reset, setValue } = useForm();
const [color, setColor] = useState({name:"", color_id:-1})
  useEffect(() => {
    getData().then((result) => {
      console.log("Got thing data", { result });
      reset({
        color_id: result.optionId,
        name: result.name
      });
      setColor( {color_id: result.optionId,
        name: result.name});
    });
  }, [reset]);

  const onSubmit = (data: any) => console.log("Form submit:", data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div style={{ width: "200px" }}>
        <div>
          <TextField
            fullWidth
            name="name"
            placeholder="Name"
            inputRef={register}
          />
        </div>
        <div>
          <Controller
            name="color_id"
            control={control}
            register={register}
            setValue={setValue}
            defaultValue={color.name}
            as={
              <Select value="name" name="color_id" fullWidth>
                {thingColors.map((tc, index) => (
                  <MenuItem key={index} value={tc.id}>
                    {tc.name}
                  </MenuItem>
                ))}
              </Select>
            }
          />
        </div>
        <p></p>
        <button type="submit">Submit</button>
      </div>
    </form>
  );
};
<Button
   handler={handleSubmit(handlerSignInButton)}
   disable={!isValid || isSubmitting}
   label={"Guardar"}
 />
我还没有使用过带有react-hook表单的材质UI,但希望这对您有所帮助

我的选择组件的示例,在Ionic React Typescript中:

import { ErrorMessage } from "@hookform/error-message";
import { IonItem, IonLabel, IonSelect, IonSelectOption } from 
"@ionic/react";
import { FunctionComponent } from "react";
import { Controller } from "react-hook-form";

type Opcion = {
  label: string;
  value: string;
};

interface Props {
  control: any;
  errors: any;
  defaultValue: any;
  name: string;
  label: string;
  opciones: Opcion[];
}

const Select: FunctionComponent<Props> = ({
  opciones,
  control,
  errors,
  defaultValue,
  name,
  label
  }) => {
    return (
      <>
        <IonItem className="mb-4">
          <IonLabel position="floating" color="primary">
            {label}
        </IonLabel>
        <Controller
          render={({ field: { onChange, value } }) => (
            <IonSelect
              value={value}
              onIonChange={onChange}
              interface="action-sheet"
              className="mt-2"
            >
                {opciones.map((opcion) => {
                   return (
                     <IonSelectOption value={opcion.value}
                       key={opcion.value}
                     >
                       {opcion.label}
                     </IonSelectOption>
                   );
                })}
            </IonSelect>
          )}
          control={control}
          name={name}
          defaultValue={defaultValue}
          rules={{
            required: "Este campo es obligatorio",
          }}
      />
    </IonItem>
      <ErrorMessage
        errors={errors}
        name={name}
        as={<div className="text-red-600 px-6" />}
      />
    </>
  );
};

export default Select;
从“@hookform/error message”导入{ErrorMessage};
从导入{IonItem、IonLabel、IonSelect、IonSelectOption}
“@离子/反应”;
从“react”导入{FunctionComponent};
从“react hook form”导入{Controller};
类型Opcion={
标签:字符串;
值:字符串;
};
界面道具{
对照组:任何;
错误:任何;
默认值:任意;