简体   繁体   English

使用 props 和 useState Hook 从 Child 中的输入更新父组件上的 state

[英]Update state on Parent component from input in Child using props and useState Hook

I am creating a multistep form using antd components, which needs to pass input values from each step Child component to the Parent's state.我正在使用 antd 组件创建一个多步骤表单,它需要将每个步骤子组件的输入值传递给父组件的 state。

Parent component:父组件:

 import React, { useState } from 'react' import { Steps, Button, message } from 'antd' import { SaveOutlined } from '@ant-design/icons' import Step1 from './Step1' import Step2 from './Step2' import Step3 from './Step3' const Step = Steps.Step const RegisterClient = () => { const [current, setCurrent] = useState(0) const [values, setValues] = useState({ companyName: '', phone: '', address: '', address2: '', postalCode: '', country: '', stateProvince: '', city: '' }) const handleOnChange = (e) => { const { name, value } = e.target setValues({...values, [name]: value }) } return ( <div className="steps-client"> <h2>Register New Client</h2> <Steps current={current}> <Step title='Company Billing Details' /> <Step title='Client Admin' /> <Step title='Billing Contact' /> </Steps> <div className="steps-content"> {current === 0 && ( <Step1 handleOnChange={ handleOnChange } values={ values } /> )} {current === 1 && ( <Step2 /> )} {current === 2 && ( <Step3/> )} </div>. . .

The problem comes when passing handleOnChange and values as props to the child component <Step1/>handleOnChangevalues作为道具传递给子组件时出现问题<Step1/>

Child component:子组件:

 import React from 'react' import { Form, Input, Row, Col } from 'antd' const Step1 = (props) => { const { handleOnChange, values } = props return ( <Form > <Row gutter={[36, 14]}> <Col span={12} > <Form.Item name='companyName' label="Company Name" rules={[ { required: true, message: 'Company Name is required.' } ]} > <Input name='companyName' placeholder= 'Company Name' value= {values.companyName} onChange= {handleOnChange('companyName')} /> </Form.Item>. . .

I get this error我收到此错误

Line 5:11:   'handleOnChange' is missing in props validation      react/prop-types
Line 5:27:   'values' is missing in props validation              react/prop-types
Line 24:29:  'values.companyName' is missing in props validation  react/prop-types

What am I missing?我错过了什么?

Change the signature of the Step1 component to:Step1组件的签名更改为:

...
import PropTypes from 'prop-types'

const Step1 = ({handleOnChange, values}) => {
...
}

You might need to install prop-types , then validate the props:您可能需要安装prop-types ,然后验证道具:

Step1.propTypes = {
  handleOnChange: PropTypes.func,
  values: PropTypes.object
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM