我正在 React JS 中开发动态表单,当用户单击“添加”按钮时,“注册”表单将添加到屏幕。在注册表格中,我使用 formik 进行验证。
表单动态添加成功,但每当我开始在输入框中输入任何内容时,我在控制台中收到以下错误:
Warning: A component is changing an uncontrolled input of type text to be
controlled. Input elements should not switch from uncontrolled to controlled
(or vice versa). Decide between using a controlled or uncontrolled input element
for the lifetime of the component.
我不确定哪里错了。下面是我的动态表单渲染代码 -
帐户.js
import React, { Component } from 'react';
import axios from 'axios';
import {
Card, CardBody, CardHeader,Button,Col, Row, Form, Container
} from 'reactstrap';
import { Formik, Field, ErrorMessage } from 'formik';
import WrapperForm from './WrapperForm'
class Account extends Component {
state = {
wrapperForm: [{}]
}
constructor(props) {
super(props);
}
addUser = () => {
this.setState((prevState) => ({
wrapperForm: [...prevState.wrapperForm, {}],
}));
}
render() {
let { wrapperForm } = this.state
return (
<Form>
<Container className="themed-container" fluid={true}>
<button type="button" onClick={this.addUser}>Add User</button>
<WrapperForm wrapperForm={wrapperForm} />
</Container>
</Form>
);
}
}
export default Account;
WrapperForm.js
const WrapperForm = (props) => {
return (
props.wrapperForm.map((val, idx)=> {
return (
<Formik
key={idx}
initialValues={{
email: props.wrapperForm[idx].email || '',
password: props.wrapperForm[idx].password || '',
firstName: props.wrapperForm[idx].firstName || '',
lastName: props.wrapperForm[idx].lastName || '',
zipCode: props.wrapperForm[idx].zipCode || ''
}}
>
{({ values }) => (
<Row style={{ marginBottom: "2em" }}>
<Card>
<CardHeader>Register</CardHeader>
<CardBody>
<Temp index={idx} />
</CardBody>
</Card>
</Row>
)}
</Formik>
)
})
)
}
Temp.js
const Temp = ({ index }) => {
let passwordId = 'password-'+ index;
let firstNameId = 'firstName-'+ index;
let lastNameId = 'lastName-'+ index;
let zipCodeId = 'zipCode-'+ index;
return (
<Card body outline color="primary">
<CardTitle>Create Profile</CardTitle>
<Row form>
<Col md={6}>
<Field
className="email"
component={customInputForm}
data-id={index}
id="email"
label="Email"
name="email"
placeholder="Email"
type="email"
/>
</Col>
</Row>
</Card>
)
}
原文由 ppb 发布,翻译遵循 CC BY-SA 4.0 许可协议
我找到了一个解决方案,也许它会对某人有所帮助。您需要为 formik 创建动态
initialValues
为: