react-hooks父组件提交子组件form

父组件:

import React, {useRef} from 'react'
import UserName from 'src/components/UserName'

interface userRef {
  submit: Function
}

const UserInfo = () => {
  const userRef = useRef()

  const checkInfo = () => {
    Promise.all([userRef.current?.submit()])
      .then(res => {
        console.log('校验成功', res)
      })
      .catch(err => {
        console.log('err', err)
      })
  }
  return (
    <>
      
      
    
  )
}

export default UserInfo

子组件

import React, {forwardRef, useEffect, useImperativeHandle, useState} from 'react'
import {useSelector} from 'react-redux'
import {Form, Input} from 'antd-mobile'

interface IProps {
  title: string
}

const UserName = forwardRef((props: IProps, ref) => {
  const [userName, setUserName] = useState('')
  const [form] = Form.useForm()
  const userInfo = useSelector((state: any) => state.userInfo)

  useEffect(() => {
    const {name} = userInfo
    if(name){
      form.setFieldsValue({
        'uName': name
      })
    }
  }, [userInfo])
  const checkSubmit = () => {
    return new Promise((resolve, reject) => {
      form
        .validateFields()
        .then(res => {
          resolve(res)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
  useImperativeHandle(ref, () => ({
    submit: checkSubmit,
  }))
  return (
    
{props.title}
setUserName(val)} />
) }) export default UserName

你可能感兴趣的:(react.js,javascript,前端)