我试图导出一个在react类组件中声明的函数,以便在另一个文件中使用它,但该函数使用了该类的道具。
这是我想要导出函数handleDeleteAction((的示例
import React, { Component } from 'react';
import { connect } from 'react-redux';
import swal from "sweetalert";
import { delete_user } from '../Actions';
class UserContainer extends Component {
constructor(props) {
super(props);
}
handleDeleteAction = async (event, { id, username }) => { // i want to export this function
await this.props.delete_user(id); //this is an action
};
renderDataTable = () => {
const { loading, data, pagination } = this.state;
return (
<DataTable
id="trace"
data={data ? data[0] : null}
totalRows={data ? data[1] : null}
columns={USER_COLUMNS} //the function is called inside the const USER_COLUMN
loading={loading}
/>
);
};
render() {
return (
<LayoutContainer renderDataTable={this.renderDataTable} title='Gestion des utilisateurs' />
);
}
export default connect(null, { loadUsersData, delete_user })(UserContainer);
并且该函数需要在该文件中调用,当用户点击按钮时就会触发:
import { Tag, Button, Space } from 'antd';
import { AiFillDelete } from "react-icons/ai";
import { BsPencil } from "react-icons/bs";
import {handleDeleteAction} from '../user/UserContainer'
export const USER_COLUMNS = [
{
title: "Action", dataIndex: "id", key: "id", align: 'center', render: (text, record, index) => {
// console.log("text", text);
// console.log("record", record);
// console.log("index", index);
return (
<Space size={'small'} >
<Button type="primary" icon={<AiFillDelete />} id={record.id} onClick={(e) => handleDeleteAction(e, record)} size='large' danger />
</Space >
);
}
}
];
您不能导出该函数。每当构造函数UserContainer
创建对象时,就会创建该函数,并且该函数是所创建对象的本地函数。您可以在类之外创建函数,甚至可以将其作为可以导出的类的方法。
export async function handleDeleteAction(event, { id, username }){
return this.props.delete_user(id);
};
class UserContainer extends Component {
constructor(props) {
super(props);
}
handleDeleteAction = handleDeleteAction.bind(this);
renderDataTable = () => {
const { loading, data, pagination } = this.state;
return (
<DataTable
id="trace"
data={data ? data[0] : null}
totalRows={data ? data[1] : null}
columns={USER_COLUMNS} //the function is called inside the const USER_COLUMN
loading={loading}
/>
);
};
render() {
return (
<LayoutContainer renderDataTable={this.renderDataTable} title='Gestion des utilisateurs' />
);
}
}
然而,这并不意味着您可以访问传递给UserContainer
类实例化的任何对象的props。导出的函数需要绑定到一个组件,该组件可以访问通过该道具传递的值。就像我们在UserContainer
课堂上所做的那样。