首页 > 解决方案 > handleChange 不适用于模态中的 formik

问题描述

我是新手,我试图在 antd 的模态中渲染一个表单,但我的 handeChange 不起作用。如果我在模态中编写所有内容,这通常可以工作,但我想知道如何通过使用不同的组件和使用 formik 来完成

const InnerForm=({
                     submitted,
                     loading,
                     errors,
                     handleSubmit,
                     handleChange,
                     values,
                     modalCancel
                 })=>
    (
        <Form className="form" onSubmit={handleSubmit}>
            <FormItem>
                <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                       placeholder="email"
                       onChange={handleChange}
                       name={"email"}
                />
            </FormItem>
            <FormItem>
                <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                       type="password"
                       placeholder="Password"
                       onChange={handleChange}
                       name={"password"}
                />
            </FormItem>
            <FormItem>
                <Button className={'button_margin'} onClick={modalCancel} type={"primary"}><Icon type="left"/>Go back</Button>
                <Button className={'button_margin'} type={"primary"}>Submit</Button>
            </FormItem>
        </Form>

    );

class App extends Component{
 constructor(props) {
        super(props);
        this.state = {
            is_authenticated: false,
            application_status_modal_visible: false,
        }
    }
handleChange =(event)=>{
        const {name,value}=event.target;
        this.setState({
            [name]: value,
        });
        console.log("handle change works");
   };
    handleSubmit=(values)=>{
    console.log(values);
    };
    modalCancel=()=>{
        this.setState({application_status_modal_visible:false})
    };
render(){
return(
<Modal
                    title="Login"
                    visible={application_status_modal_visible}
                    footer={null}
                   >
                    <Formik onSubmit={this.handleSubmit}
                            handleChange={this.handleChange}
                            render={formikProps =>
                                <InnerForm
                                    modelCancel={this.modalCancel}
                                    {...formikProps}
                                />
                            }/>
                </Modal>)
}
}

export default connect()(App)

我希望这个输出 {email:"abc@gmail.com",password:"1234567"}

标签: reactjsantdformik

解决方案


<Formik>组件不接受 prop handleChange;它传递了一个调用的渲染道具handleChange,您可以以自定义方式使用它,就像这样(我没有列出所有其他必需的道具):

<Formik>
  ({ handleChange }) => (
    <input
     onChange={
      (e) => { 
        /* custom stuff */ 
        handleChange(e)}
       } 
    />
   )
</Formik>

推荐阅读