react-admin中的芯片输入

时间:2019-01-28 10:12:40

标签: 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;

2 个答案:

答案 0 :(得分:1)

工作代码

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;

答案 1 :(得分:1)

以下是使用 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