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

React 18中如何调用函数组件内部函数?含ReactDataGrid场景

解决方案

问题核心是你把columns定义在RoomDeposit组件外部了,外部代码无法访问组件内部的setCurrencyValue和gridRef。只需要把columns的定义移到组件内部,就能直接引用组件内的函数与ref了。

修改后的完整代码如下:

import React, { useState } from 'react';
import ReactDataGrid from '@inovua/reactdatagrid-community';
import SelectEditor from '@inovua/reactdatagrid-community/SelectEditor'; // 补全SelectEditor的导入

const RoomDeposit = () => {
  const [gridRef, setGridRef] = useState(null);
  const [dataSource, setDataSource] = useState([/* 这里放你的数据源初始数据 */]);

  const setCurrencyValue = () => {
    gridRef.current.setItemPropertyAt(2, 'amount', '20');
  };

  // 将columns移至组件内部,使其能访问setCurrencyValue
  const columns = [
    // ...其他列的配置
    {
      name: 'currency_id',
      groupBy: false,
      defaultFlex: 1,
      maxWidth: 150,
      textAlign: 'center',
      header: 'Currency',
      editor: SelectEditor,
      editable: true,
      editorProps: {
        dataSource: ['Dollar', 'Euro', 'Pound', 'INR'].map((element) => ({
          id: element,
          label: element
        })),
        setClientonChange() {
          // 直接调用组件内的setCurrencyValue
          setCurrencyValue();
          // 若需要获取选中的选项值,可给函数加参数:
          // setClientonChange(selectedItem) {
          //   console.log('选中的选项:', selectedItem);
          //   setCurrencyValue();
          // }
        }
      }
    }
  ];

  return (
    <ReactDataGrid
      onReady={setGridRef}
      columns={columns}
      dataSource={dataSource}
    />
  );
};

export default () => <RoomDeposit />;

额外补充:

  • 确保补全SelectEditor的导入,否则编辑器无法正常渲染
  • 如果你的数据源是动态的,建议用useState管理(如代码中所示)
  • 若需要在下拉框变化时获取选中值,可给setClientonChange添加参数,直接拿到选中的选项对象

内容的提问来源于stack exchange,提问作者bharathitm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:50:44