Typescript结合form表单使用时怎么同时继承父组件this.props和form的this.props.form
正常的JS中使用如下:
import { Form } from 'antd';
const FormItem = Form.Item;
...
//CustomedForm类组件中使用
render(){
const { getFieldDecorator } = this.props.form;//正常引入getFieldDecorator
return(
<Form>
<FormItem>
{getFieldDecorator('keyword', {
rules: [{ required: true, message: '请选择XXX' }],
})(
...todo
)}
</FormItem>
</Form>
)
}
//暴漏CustomedForm类组件
export default Form.create({
mapPropsToFields: (props) => ({
source: Form.createFormField({
...props.source,
value: props.source.value,
})
...
})(CustomedForm);
Typescript中使用报错如下:
页面报错:ReferenceError: getFieldDecorator is not defined,
控制台报错:OpinionsComp.tsx:80 Uncaught ReferenceError: getFieldDecorator is not defined
Antd官方说明如下:(核心代码)
(1)引入FormComponentProps :import { FormComponentProps } from ‘antd/lib/form’;
(2)使用ts定义类型时继承刚才的引入模块,如果没有使用ts,可以忽略该步骤:
import { Form } from 'antd';
import { FormComponentProps } from 'antd/es/form';
interface UserFormProps extends FormComponentProps {
age: number;
name: string;
}
class UserForm extends React.Component<UserFormProps, any> {
// ...
}
const App = Form.create<UserFormProps>({
// ...
})(UserForm);
正常Antd使用如上,结合this.props和this.props.form使用:
import { FormComponentProps } from 'antd/lib/form'//TSX引入这句话
interface IProps { //接受父组件传过来的参数
map: any
onClose?: (currentCom) => void
viewConfig?: any
}
function DisasterEvaluation(props: IProps) {//组件接受父组件传参
return (
<div >
<DisasterEvaluationFormApp map={props.map} view={props.viewConfig!.activeView} mapContainer={props.viewConfig!.container} />
</div>
)
}
export default DisasterEvaluation//正常暴漏
interface IDisasterEvaluationFormProps extends FormComponentProps {//继承引入的模块
map: any
view: any
mapContainer: any
}
class DisasterEvaluationForm extends React.Component<IDisasterEvaluationFormProps, IState> {//修改IDisasterEvaluationFormProps
map = this.props.map
view = this.props.view
mapContainer = this.props.mapContainer
constructor(props: IDisasterEvaluationFormProps) {//修改IDisasterEvaluationFormProps
super(props)
this.state = {
...
}
}
}
const DisasterEvaluationFormApp = Form.create<IDisasterEvaluationFormProps>({})(DisasterEvaluationForm)//绑定