React.js Material-Table 将选定的行传递到另一个页面

React.js Material-Table pass selected rows to another page

如何将选定的行数据作为 prop 传递到另一个页面?

我正在使用 material-table,我想在单击“导出”按钮后将选定的行数据传递到另一个页面,这样我就可以使用该数据创建一些类型另一页的报告。

我想我应该使用 history.push() 方法,但它在 onClick 方法中不起作用。有人可以给我任何提示吗?

import React from 'react'
import MaterialTable from 'material-table';

class LeadTable extends React.Component{
    constructor(props) {  
      super(props);
      this.state = { 
        leads : [],
      };
    }
  
    componentDidMount() {
      fetch('http://localhost:5000/api/Leads')
      .then(res => res.json())
      .then((data) => {
        // console.log('Data: ', data[0])
        this.setState({
          leads: data[0]
        })
      })
      .catch(console.log);
    }

    redirectToReport = () => {
      const { history } = this.props;
      history.push('report');
    }

    render(){
      return (
        <div style={{ maxWidth: '100%' , align: 'center'}}>
          <MaterialTable
            title="Reporting"
            columns={[
              ...
            ]}
            data = {this.state.leads}       
            options={{
              selection: true,
              filtering: true,
              sorting: true
            }}
            actions = {[{
              position: "toolbarOnSelect",
              
              tooltip: 'Export the selected activities!',
              icon: 'Export',
  
              onClick: (event, rowData) => {
                console.log("Row Data: " , rowData)
                // rowData has all the selected row and I want to redirect to another page with passing those data.
              }
            }]}
          />
        </div>
    )}
}

export default LeadTable

这个答案主要针对使用 class 组件的 OP 代码库。如果您正在使用功能组件,您可以使用 react-router hooks 例如 useHistory


使用 withRouter HOC 启用 LeadTable 组件访问 history 这样你就可以 push

const LeadTableWithRouter = withRouter(LeadTable);

将对象传递给push函数以传递行数据

redirectToReport = (rowData) => {
  const { history } = this.props;
  history.push({
    pathname: "/report", // re-route to this path
    state: { name: rowData.name, surname: rowData.surname } // your row data
  });
};

在您的其他组件中,使用 this.props.location.state.<data_name> 访问您传递的行数据

class AnotherPage extends React.Component {
  render() {
    return (
      <>
        <p>{this.props.location.state.name}</p>
        <p>{this.props.location.state.surname}</p>
        <Link to="/">go back</Link>
      </>
    );
  }
}