我自定义蚂蚁设计表单控件时,Typescript的道具类型是什么

时间:2019-06-21 03:13:23

标签: reactjs typescript antd

我的表单组件代码在这里:

import * as React from 'react';
import { From } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import CustomControl from './CustomControl'

interface IProps extends FormComponentProps {

}

class MyForm extends React.Component<IProps> {
  constructor(props: IProps) {
    super(props);
  }

  public render(): React.ReactNode {
    const { getFieldDecorator } = this.props.form

    return <Form>
      <Form.Item label="custom-control">
        {
          getFieldDecorator('custom-field', {initialValue: 'custome-value'})
          (<CustomControl />)
        }
      </Form.Item>
    </Form>
  }
}

export default Form.create<IProps>()(MyForm);

我的自定义表单控件在这里:

import * as React from 'react';
import { Input } from 'antd';

const { forwardRef, useState } = React;

function CustomControl(props: any) {
    const [value, setValue] = useState(props.value);
    const handleChange = (value: string) => {
        if (props.onChange) {
            setValue(value)
            props.onChange(value)
        }
    }

    return <div>
        <Input value={value} onChange=((e) => handleChange(e.currentTarget.value)) />
    </div>
}
export default forwardRef(CustomControl)

是这个any

function CustomComponent(props: any) {}

我无法定义antd getFieldDecorator传递的道具的类型,这是有关getFieldDecorator的代码:

getFieldDecorator<T extends Object = {}>(id: keyof T, options?: GetFieldDecoratorOptions): (node: React.ReactNode) => React.ReactNode;

React.ReactNode显然不适合我。

所以,我只能在这里写any,不够友善。

请告诉我优化此any的方法。

1 个答案:

答案 0 :(得分:0)

方案1:必备道具

如果CustomControl具有必需的道具,则可以这样输入。

type Props = {
  value: string;
  onChange: Function;
};

function CustomControl(props: Props) { /* code omitted for clarity */ }

由于需要道具,因此在将CustomControl传递到getFieldDecorator时,应包括道具。

<Form.Item label="custom-control">
  {getFieldDecorator("custom-field", {
    initialValue: "custome-value"
  })(<CustomControl value="foo" onChange={() => { /* do something */ }} />)}
</Form.Item>

方案2:可选道具

如果CustomControl具有可选的道具,那么您可以像这样使它们成为可选的?

type Props = {
  value?: string;
  onChange?: Function;
};

function CustomControl(props: Props) { /* code omitted for clarity */ }

由于道具现在是可选的,因此在将CustomControl传递到getFieldDecorator时不再需要包含它们。

<Form.Item label="custom-control">
  {getFieldDecorator("custom-field", {
    initialValue: "custome-value"
  })(<CustomControl />)}
</Form.Item>