ant design pro 组件通信

本文详细解析了Ant Design中Form组件的高级用法,包括如何在一个页面中正确处理多个表单,避免数据混淆,以及如何在父组件与子组件间通过props和回调函数进行数据传递和状态同步,确保表单数据的准确提交。

描述:在页面(组件)中,只能有一个@Form.create(),意味着this.props.form唯一,如果一个页面有两个或者多个表单,提交其中一个,会携带其他表单数据,如果设置了required: true,影响其他表单提交,此时就需要新建组件。

情况一(子组件调用父组件方法):

//顶部搜索,点击搜索动作在子组件内部完成,需要把搜索条件传给父组件保存(分页需要)
import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Input, Button ,Modal } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './PatientManagement.less';
import stylesUtil from '../../utils/utils.less';
import { emptyVal, defaultPageSize } from '../../utils/utils';

@connect(({ patientManagement, loading ,}) => ({
  patientManagement,
  loading: loading.models.patientManagement,
  submitting: loading.effects['form/submitAdvancedForm'],
}))
@Form.create()
export default class PatientManagement extends PureComponent {
  state = {
    searchVal:'' //分页需要该参数 ,请看分页那一篇博客
  };
  
  componentDidMount() {
  }
  
  setVal = (val) => { //子组件传值
    this.setState({searchVal:val})
  };
  
    render() {
    const { patientManagement: { data }, loading, form } = this.props;

    return (
      <PageHeaderLayout>
               {//父组件传个方法过去,子组件接收,利用其传值}
              <Search dispatch={this.props.dispatch}  setVal={this.setVal}></Search>
      </PageHeaderLayout>
    );
  }
}
//搜索组件
class Search extends PureComponent {
  state ={
  }
  onValidateForm = (e) => {
    const { validateFields } = this.props.form;
    const { setVal } = this.props //重要
    validateFields((err, values) => {
      if (!err) {
        setVal(values) //使用接收的方法 重要
        this.props.dispatch({
            type: 'patientManagement/getAllList',
            payload: values,
        });
      }
    });
  }

  render(){
    const { getFieldDecorator, getFieldValue } = this.props.form;
    return (
      <Form onSubmit={this.onValidateForm} layout="inline">
          <FormItem label="姓名">
            {getFieldDecorator('name', {
              rules: [{ required: false, message: '请输入' }],
            })(
              <Input placeholder="请输入姓名" />
            )}
          </FormItem>             
          <Button type="primary" htmlType="submit">查询</Button>
      </Form>
    );
  }
}
Search = Form.create()(Search)//重要

情况二(父组件调用子组件方法):

//使用场景,在Modal 中,想点击Modal 确认按钮,控制子组件表单提交。
import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Card, Tabs, Table, Form, Input, Button, DatePicker, message, Row, Col, Modal ,Carousel ,Icon ,Select ,Popconfirm, Divider } from 'antd';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import BizGiveForm from '../../components/BizGiveForm';
import styles from '../../utils/utils.less';
import { emptyVal, defaultPageSize, fileHost, imageHost } from '../../utils/utils';

@connect(({ receipt, loading }) => ({
  receipt,
  loading: loading.models.receipt,
}))
@Form.create()
export default class Receipt extends PureComponent {
  state = {
  };

  componentDidMount() {
   
    }
    
  getThis= (ref)=>{
    this.myForm = ref        //接收子组件this
  }
  
  okk =()=>{
    this.myForm.test()    //this.myForm 即 子组件
  }

  render() {
    return (
      <PageHeaderLayout>
          <span onClick={this.okk}>点我666,我是Modal确认按钮</span>
          <MyForm getThis={this.getThis}  ></MyForm>
      </PageHeaderLayout>
    );
  }
}
//组件
class MyForm extends PureComponent {
  state ={
  }
  componentDidMount(){
    this.props.getThis(this) //传this过去,是的父组件可以通过其调用方法
  }

  test = ()=>{
    console.log('真的可以啊,6666,点我提交表单')
  }
  render(){
    return (
      <div>假如,我是一个表单</div>
    );
  }
}
MyForm = Form.create()(MyForm)
Ant Design Pro 中,组件间传值是常见需求,可以通过多种方式实现。以下是详细的传值方法及示例: --- ### **1. 父组件 → 子组件Props)** 直接通过 `props` 传递数据或函数。 #### 示例 ```tsx // 父组件 import React from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const [count, setCount] = useState(0); return ( <ChildComponent value={count} onIncrement={() => setCount(count + 1)} /> ); }; // 子组件 (ChildComponent.tsx) import React from 'react'; interface Props { value: number; onIncrement: () => void; } const ChildComponent: React.FC<Props> = ({ value, onIncrement }) => ( <div> <p>Count: {value}</p> <button onClick={onIncrement}>Increment</button> </div> ); ``` --- ### **2. 子组件 → 父组件(回调函数)** 通过父组件传递的回调函数,子组件触发父组件状态更新。 #### 示例 ```tsx // 父组件 const ParentComponent = () => { const [message, setMessage] = useState(''); const handleChildSubmit = (text: string) => { setMessage(text); }; return ( <div> <ChildComponent onSubmit={handleChildSubmit} /> <p>子组件传来的值: {message}</p> </div> ); }; // 子组件 interface Props { onSubmit: (text: string) => void; } const ChildComponent: React.FC<Props> = ({ onSubmit }) => { const [inputValue, setInputValue] = useState(''); return ( <div> <input value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <button onClick={() => onSubmit(inputValue)}>提交</button> </div> ); }; ``` --- ### **3. 兄弟组件间传值(状态提升)** 将共享状态提升到共同的父组件,通过 Props 传递给子组件。 #### 示例 ```tsx // 父组件 const ParentComponent = () => { const [sharedData, setSharedData] = useState(''); return ( <div> <SiblingA onUpdate={setSharedData} /> <SiblingB data={sharedData} /> </div> ); }; // 兄弟组件A (修改数据) const SiblingA = ({ onUpdate }: { onUpdate: (data: string) => void }) => ( <button onClick={() => onUpdate("来自兄弟A的数据")}>更新数据</button> ); // 兄弟组件B (显示数据) const SiblingB = ({ data }: { data: string }) => ( <p>接收到的数据: {data}</p> ); ``` --- ### **4. 跨层级组件传值(Context)** 使用 React Context 避免多层 Props 传递。 #### 示例 ```tsx // 创建 Context const MyContext = React.createContext<{ value: string; setValue: (val: string) => void; } | undefined>(undefined); // 父组件 const ParentComponent = () => { const [value, setValue] = useState("初始值"); return ( <MyContext.Provider value={{ value, setValue }}> <DeepChildComponent /> </MyContext.Provider> ); }; // 深层子组件 const DeepChildComponent = () => { const context = useContext(MyContext); if (!context) return null; const { value, setValue } = context; return ( <div> <p>Context值: {value}</p> <button onClick={() => setValue("新值")}>修改Context</button> </div> ); }; ``` --- ### **5. 全局状态管理(Redux/Model)** 在 Ant Design Pro 中,推荐使用 **Umi + Dva**(或 **Redux Toolkit**)管理全局状态。 #### 示例(Dva Model) ```ts // src/models/example.ts export default { namespace: 'example', state: { value: '', }, reducers: { updateValue(state, action) { return { ...state, value: action.payload }; }, }, }; // 组件A (发送数据) import { connect, Dispatch } from 'umi'; const ComponentA = ({ dispatch }: { dispatch: Dispatch }) => ( <button onClick={() => dispatch({ type: 'example/updateValue', payload: 'Hello' })}> 发送数据 </button> ); // 组件B (接收数据) const ComponentB = ({ value }: { value: string }) => ( <p>全局状态值: {value}</p> ); export default connect(({ example }: { example: { value: string } }) => ({ value: example.value, }))(ComponentB); ``` --- ### **6. 路由参数传值** 通过 `umi` 的 `history` 或 `useParams` 传递参数。 #### 示例 ```tsx // 跳转时传参 import { history } from 'umi'; history.push('/target-path?id=123'); // 或 history.push({ pathname: '/target-path', query: { id: '123' } }); // 目标页面获取参数 import { useLocation } from 'umi'; const TargetPage = () => { const location = useLocation(); const query = new URLSearchParams(location.search); const id = query.get('id'); // "123" return <div>ID: {id}</div>; }; ``` --- ### **7. 事件总线(Event Emitter)** 适用于非父子组件的临时通信(需谨慎使用,避免滥用)。 #### 示例 ```ts // event.ts import { EventEmitter } from 'events'; export const eventBus = new EventEmitter(); // 组件A (发送事件) eventBus.emit('message', { text: 'Hello' }); // 组件B (监听事件) useEffect(() => { const handler = (data: { text: string }) => console.log(data.text); eventBus.on('message', handler); return () => eventBus.off('message', handler); }, []); ``` --- ### **总结** | 场景 | 推荐方式 | |--------------------|--------------------------| | 父子组件传值 | Props / 回调函数 | | 兄弟组件传值 | 状态提升 | | 跨层级组件 | Context | | 全局状态共享 | Redux / Dva Model | | 路由参数传递 | `umi` 的 `history` | | 临时跨组件通信 | 事件总线(慎用) | 根据具体场景选择合适的方式,Ant Design Pro 中优先使用 **Dva Model** 或 **Context** 管理复杂状态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘斩仙的笔记本

富贵险中求

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值