react-admin 中的芯片输入

Chip input in react-admin

如何在react-admin中使用material-ui-chip-input?

我尝试编写这样的代码,但结果没有向服务器发送任何内容。

import React from 'react';
import { Field } from 'redux-form';
import ChipInput from 'material-ui-chip-input';

const renderChipInput = ({ input, meta: { touched, error } }) => (
        <ChipInput {...input}/>

);
const Chip = () => <Field name="tags" component={renderChipInput} />
export default Chip;

有效码

import React from 'react';
import { Field } from 'redux-form';
import ChipInput from 'material-ui-chip-input';

const renderChipInput = ({ input, meta: { touched, error } }) => (
        <ChipInput {...input}
                   value = { input.value || []}
                   onAdd={(addedChip) => {
                       let values = input.value || [];
                       values = values.slice();
                       values.push(addedChip);
                       input.onChange(values);
                   }}
                   onDelete={(deletedChip) => {
                       let values = input.value || [];
                       values = values.filter(v => v !== deletedChip);
                       input.onChange(values);
                   }}
                   onBlur={() => input.onBlur()}
        />
);
const Chip = () => <Field name="tags" component={renderChipInput} />
export default Chip;

这是一个使用 useFieldreact-admin@^3.0.0 的示例实现:

import React from 'react';
import { useInput } from 'react-admin';
import RawChipInput from 'material-ui-chip-input';

export function ChipInput(props) {
  const {
    input: { value, onChange, ...rest },
    meta: { touched, error },
    isRequired,
  } = useInput(props);

  if (value && !Array.isArray(value)) {
    throw new Error(
      `ChipInput requires an array value but received: ${JSON.stringify(
        value,
      )}`,
    );
  }

  return (
    <RawChipInput
      value={value || []}
      label={props.label}
      onAdd={(newChip) => onChange((value || []).concat(newChip))}
      onDelete={(deletedChip) =>
        onChange((value || []).filter((item) => item !== deletedChip))
      }
      error={!!(touched && error)}
      helperText={touched && error}
      required={isRequired}
      {...rest}
    />
  );
}

官方文档中关于自定义输入的更多信息:https://marmelab.com/react-admin/Inputs.html#the-useinput-hook