我想用React,Typescript和Gatsby编写联系表单。 我编写了表单处理代码,但是有一个问题。我无法解决在使用者中未定义上下文的问题。我已经放置了上下文值,但是VScode不会重新定义它。我该如何忍受呢?谢谢。 我正在使用react16。我制作每个模型文件和tsx文件。 此上下文不起作用。错误消息在
下面import React from 'react';
import { FieldProps, FormContext, IFormContext, Errors } from '../../models/form';
const Field: React.SFC<FieldProps> = ({ id, label, editor, options, value }) => {
const getError = (errors: Errors): string => (errors ? errors[id] : '');
const getEditorStyle = (errors: Errors): any => (getError(errors) ? { borderColor: 'red' } : {});
return (
<FormContext.Consumer>
{(context: IFormContext) => (
...
)}
</FormContext.Consumer>
);
};
Field.defaultProps = {
editor: 'textbox',
};
export default Field;
export interface IFormContext extends FormState {
setValues: (values: Values) => void;
validate: (fieldName: string) => void;
}
export const FormContext = React.createContext<IFormContext | undefined>(undefined);
import React from 'react';
import { FormProps, FormState, Errors, Values, FormContext } from '../../models/form';
class Form extends React.Component<FormProps, FormState> {
.....
render() {
const { submitSuccess, errors } = this.state;
const context = {
...this.state,
setValues: this.setValues,
validate: this.validate,
};
return (
<FormContext.Provider value={context}>
<form onSubmit={this.handleSubmit} noValidate={true}>
<div className="container">
{this.props.render()}
....
)}
</div>
</form>
</FormContext.Provider>
);
}
}
export default Form;