【发布时间】:2019-12-05 14:34:20
【问题描述】:
我的 React (TypeScript) 应用程序有以下模型:
interface IProjectInput {
id?: string;
name: string | i18n;
description: string | i18n;
}
export interface i18n {
[key: string]: string;
}
我正在使用Formik 和react-bootstrap 从Form 创建一个新的ProjectInput:
import { i18n as I18n, ... } from 'my-models';
interface State {
validated: boolean;
project: IProjectInput;
}
/**
* A Form that can can edit a project
*/
class ProjectForm extends Component<Props, State> {
constructor(props: any) {
super(props);
this.state = {
project: props.project || {
name: {},
description: ''
},
validated: false
};
}
async handleSubmit(values: FormikValues, actions: FormikHelpers<IProjectInput>) {
let project = new ProjectInput();
project = { ...project, ...values };
console.log("form values", values);
// actions.setSubmitting(true);
// try {
// await this.props.onSubmit(project);
// } catch (e) { }
// actions.setSubmitting(false);
}
render() {
const { t } = this.props;
const getCurrentLng = () => i18n.language || window.localStorage.i18nextLng || '';
const init = this.state.project || {
name: {},
description: ''
};
return (
<div>
<Formik
// validationSchema={ProjectInputSchema}
enableReinitialize={false}
onSubmit={(values, actions) => this.handleSubmit(values, actions)}
initialValues={init}
>
{({
handleSubmit,
handleChange,
handleBlur,
values,
touched,
errors,
isSubmitting,
setFieldTouched
}) => {
return (
<div className="project-form">
<Form noValidate onSubmit={handleSubmit}>
<Form.Row>
<Form.Group as={Col} md={{span: 5}} controlId="projectName">
<Form.Label>
{t('projectName')}
</Form.Label>
// Input for ENGLISH text
<Form.Control
type="text"
name="name"
value={(values['name'] as I18n).en}
onChange={handleChange}
/>
// Input for FRENCH text
<Form.Control
type="text"
name="name"
value={(values['name'] as I18n).fr}
onChange={handleChange}
/>
</Form.Group>
所以最后应该是这样的:
{
"name": {
"en": "yes",
"fr": "oui"
},
"description" : "test",
...
}
我的问题是,name 输入的值保持为空。
我尝试在我的render 或我的state 中添加const init = this.state.project || { name: { 'en': '' },,但这没有任何作用。
【问题讨论】:
标签: javascript reactjs typescript formik