You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中向下两层传递带参数函数的实现方法咨询

React ConfirmationBox组件:接收带参数的函数Props并触发调用

看起来你已经有了一个基础的ConfirmationBox组件雏形,我帮你补全并实现你想要的功能——让组件能接收带参数的函数作为props,点击确认按钮时调用该函数并传入参数。

完整实现代码

import React, { Component } from 'react';
import { Button, Modal } from 'semantic-ui-react';

class ConfirmationBox extends Component {
  state = { modalOpen: false };

  handleOpen = () => {
    this.setState({ modalOpen: true });
  };

  handleClose = () => {
    this.setState({ modalOpen: false });
  };

  // 处理确认按钮点击:调用传入的函数并传参,然后关闭模态框
  handleConfirm = () => {
    // 调用props传入的带参函数,用可选链避免函数未传入时报错
    this.props.onConfirm?.(this.props.confirmParams);
    this.handleClose();
  };

  render() {
    const { modalOpen } = this.state;
    // 从props接收自定义内容,让组件更通用
    const { title = '确认操作', content = '你确定要执行这个操作吗?' } = this.props;

    return (
      <>
        {/* 触发模态框的按钮,文本支持自定义 */}
        <Button onClick={this.handleOpen}>{this.props.buttonText || '确认操作'}</Button>
        <Modal
          open={modalOpen}
          onClose={this.handleClose}
          basic
          size='small'
        >
          <Modal.Header>{title}</Modal.Header>
          <Modal.Content>
            <p>{content}</p>
          </Modal.Content>
          <Modal.Actions>
            <Button basic color='red' onClick={this.handleClose}>
              取消
            </Button>
            <Button color='green' onClick={this.handleConfirm}>
              确认
            </Button>
          </Modal.Actions>
        </Modal>
      </>
    );
  }
}

export default ConfirmationBox;

关键功能说明

  • 接收带参函数Props:组件通过this.props.onConfirm接收你需要触发的函数,通过this.props.confirmParams接收要传递的参数(你也可以根据需求直接在handleConfirm里写死参数,或者传递多个参数)
  • 安全调用函数:使用?.可选链操作符,确保如果父组件没有传入onConfirm函数时,不会抛出错误
  • 通用化扩展:额外添加了标题、提示文本、按钮文本的props传递,让这个组件能适配更多业务场景

父组件使用示例

// 在父组件中使用ConfirmationBox
import ConfirmationBox from './ConfirmationBox';

class ParentComponent extends Component {
  // 定义带参数的业务函数
  handleConfirmAction = (params) => {
    console.log('确认操作触发,参数:', params);
    // 这里可以编写你的业务逻辑,比如发送删除请求、修改状态等
  };

  render() {
    return (
      <div>
        <ConfirmationBox
          buttonText='删除用户'
          title='确认删除'
          content='删除后无法恢复,确定要继续吗?'
          // 传递带参函数
          onConfirm={this.handleConfirmAction}
          // 传递要传入的参数
          confirmParams={{ userId: 123, userName: '张三' }}
        />
      </div>
    );
  }
}

这样当你点击"删除用户"按钮,弹出模态框后点击"确认",就会调用handleConfirmAction并传入{ userId: 123, userName: '张三' }这个参数啦。

内容的提问来源于stack exchange,提问作者Jens-Konrad Preem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:49:09