当用户单击“添加按钮注册”表单添加到屏幕时,我正在React Web中进行动态开发。在注册表单中,我正在使用formik集成进行验证。表单是动态成功添加的,但是每当我开始在输入框中输入任何内容时,控制台中都会出现以下错误
index.js:1 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.
我不确定哪里出了问题。以下是我的动态表单呈现代码-
Account.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 = (e) => {
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
type="email"
label="Email"
name="email"
data-id={index}
placeholder="Email"
component={customInputForm}
id="email"
className="email"
/>
</Col>
答案 0 :(得分:3)
我找到了一种解决方案,可能会帮助某人-
需要为formik创建动态initialValues
,例如-
let passwordId = 'password-'+ idx ;
let firstNameId = 'firstName-'+ idx;
let lastNameId = 'lastName-'+ idx;
let zipCodeId = 'zipCode-'+ idx;
return (
<Formik
key={idx}
initialValues={{
email: props.wrapperForm[idx].email || '',
[passwordId]: props.wrapperForm[idx].password || '',
[firstNameId]: props.wrapperForm[idx].firstName || '',
[lastNameId]: props.wrapperForm[idx].lastName || '',
[zipCodeId]: props.wrapperForm[idx].zipCode || ''
}}
>