使用反应钩子形式删除不受控制的“ChipInput”中的标签

时间:2021-01-25 11:58:53

标签: javascript reactjs react-hook-form

我正在使用 react-hook-form 来处理表单值,它适用于所有其他输入类型,如 TextFeild,从材料中选择,但面临“材料用户界面芯片输入”的问题,因为添加标签工作正常,但无法通过单击十字按钮或按退格键删除标签。我一直在为此苦苦挣扎。任何人都请帮忙。

import React from "react";
import FormControl from "@material-ui/core/FormControl";
import { Controller } from "react-hook-form";

import ChipInput from "material-ui-chip-input";

const ReactHookFormChips = ({
  name,
  label,
  control,
  defaultValue,
  children,
  rules,
  error,
  chipsError,
  ...props
}) => {
  const labelId = `${name}-label`;
  return (
    <FormControl {...props}>
      <Controller
        as={
          <ChipInput
            label={label}
            helperText={chipsError}
            error={error}
          />
        }
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={rules}
      />
    </FormControl>
  );
};
export default ReactHookFormChips;


像这样调用这个组件

<ReactHookFormChips
  id="levelLabel"
  name="tags"
  label="Select Tags"
  control={control}
  defaultValue={[]}
  margin="normal"
  error={!!errors?.tags}
  rules={{ required: true }}
  chipsError={errors?.tags && "Tag is required."}
/>

1 个答案:

答案 0 :(得分:2)

我使用渲染道具修复了它。

import React from "react";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import { Controller } from "react-hook-form";

import ChipInput from "material-ui-chip-input";

const ReactHookFormChips = ({
  name,
  label,
  control,
  defaultValue,
  children,
  rules,
  error,
  chipsError,
  ...props
}) => {
  const labelId = `${name}-label`;
  return (
    <FormControl {...props}>
      <Controller
        render={({ onChange, onBlur, value }) =>
          <ChipInput
            onChange={onChange}
            label={label}
            helperText={chipsError}
            error={error}
          />
        }
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={rules}
      />
    </FormControl>
  );
};
export default ReactHookFormChips;