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
的方法。
答案 0 :(得分:0)
如果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>
如果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>