1. 程式人生 > 其它 >react-hooks父元件提交子元件form

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

父元件:

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

interface userRef {
  submit: Function
}

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

  const checkInfo = () => {
    Promise.all([userRef.current?.submit()])
      .then(res => {
        console.log(
'校驗成功', res) }) .catch(err => { console.log('err', err) }) } return ( <> <UserName title={'使用者姓名'} ref={userRef} /> <button onClick={checkInfo}> </button> </> ) } 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 ( <Form layout='horizontal' form={form}> <div>{props.title}</div> <Form.Item name='uName' label='姓名' required rules={[ {required: true, message: '姓名不能為空'}, {pattern: /^[a-zA-Z0-9,\u4e00-\u9fa5]+$/, message: '不可包含特殊字元'}, ]}> <Input placeholder='請輸入姓名' value={userName} onChange={val => setUserName(val)} /> </Form.Item> </Form> ) }) export default UserName