首页 > 解决方案 > 根据用户对 React Hook Form 的输入显示条件信息

问题描述

我有一个 React 表单,我希望用户能够根据他们在表单中选择的选项来控制 div 的内容。我希望这发生在 onChange 上。

例如:如果用户在选择字段中输入“布丁”,则 div 将显示布丁列表,例如冰淇淋、蛋糕、苹果碎。如果用户输入“主菜”,该 div 将显示主菜列表,例如牛排、鸡肉、火腿。

这个概念看起来很简单,但我是 React 新手,而且更复杂的是我正在使用React Hook Form并且需要使用控制器,因为我将使用条件逻辑来显示和隐藏表单字段。话虽如此,我不确定这是否相关?!

应用结构

  ----index.js---- 
   V             V
Form.js     MenuItems.js
   V
FormSelect.js

表单选择.js

import React from 'react';
import { Select, MenuItem } from '@material-ui/core';
import { Controller } from 'react-hook-form';
function FormSelect({ values, name, question, register, control }) {
  const selectOptions = values;
  return (
    <div className="form-group">
      <label htmlFor={name}>What part of the menu do you want to see?</label>
      <Controller
        as={
          <Select>
               <MenuItem value="puddings">Puddings</MenuItem>
               <MenuItem value="mains">Mains</MenuItem>
          </Select>
        }
        control={control}
        name={name}
        register={register}
        className="form-control"
        id={name}
        defaultValue=""
      />
    </div>
  );
}
export default FormSelect;

MenuItems.js

import React from 'react;
const MenuItems = probs =>{
    return <div>This is where I want to show the list of foods!</div>;
};
export default MenuItems;

有没有人可以建议我需要对我的代码做些什么来完成这项工作?

非常感谢,

凯蒂

标签: reactjsreact-hooksonchangereact-hook-form

解决方案


推荐阅读