使用props和useState Hook

时间:2020-06-10 18:04:07

标签: reactjs react-hooks antd react-props

我正在使用antd组件创建一个多步骤表单,该表单需要将输入值从每个步骤Child组件传递到Parent的状态。

父组件:

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>
      .
      .
      .

handleOnChangevalues作为道具传递给子组件<Step1/>

时出现问题

子组件:

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>
          .
          .
          .

我收到此错误

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

我想念什么?

1 个答案:

答案 0 :(得分:1)

Step1组件的签名更改为:

...
import PropTypes from 'prop-types'

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

您可能需要安装prop-types,然后验证道具:

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