在按钮单击 React 上使用道具路由到新组件

Route to new component with props on button click React

单击按钮后,我需要将新道具传递给 UnitOverview,然后转到 link“OeeUnitOverview”。当我转到组件的 link "OeeUnitOverview 时,将自动加载。 我想在 OeeUnitOverview class

中打印 ID 和名称
<Button
  component={Link}
  to="OoeUnitOverview"
  // render={(props) => <UnitOverview id={5} name={"test"} {...props} />}
  // ///  <== not working
  variant="contained"
  style={{ width: "100%" }}
>
  Detailscode
</Button>

class UnitOverview extends React.Component<IUnitProps> {
  constructor(props: IUnitProps) {
    super(props);
  }

  componentDidMount() {
    // console.log("UnitOverview id " + this.state.name);
    console.log("id = " + this.props.id);
    console.log("name = " + this.props.name);
  }
  render() {
    return <h1>test</h1>;
  }
}
interface IUnitProps {
  id: number;
  name: string;
  history?: any;
  location?: any;
  match?: any;
}

export default UnitOverview;

我猜你正在使用 react-router-dom。使用 Link 组件,您可以传递路由状态。 Link: to object.

<Button
  component={Link}
  to={{
    pathname: "OoeUnitOverview",
    state: {
      id: 5,
      name: 'test',
    },
  }}
  variant="contained"
  style={{ width: "100%" }}
>
  Detailscode
</Button>

然后在接收路由(渲染UnitOverview)上,确保它可以访问route props或路由器上下文。路线状态将在 location prop/object.

this.props.location.state
// or props.location.state
// or const { state } = useLocation();

基于界面

interface IUnitProps {
  id: number;
  name: string;
  history?: any;
  location?: any;
  match?: any;
}

我假设它正在正确接收路由道具。使用 componentDidMount 生命周期方法访问传递的路由状态并处理依赖于它们的任何逻辑。

class UnitOverview extends React.Component<IUnitProps> {
  constructor(props: IUnitProps) {
    super(props);
  }

  componentDidMount() {
    const {
      location: {
        state,
      },
    } = this.props;

    console.log("id = " + state.id);
    console.log("name = " + state.name);
  }

  render() {
    return <h1>test</h1>;
  }
}

如果您看到 props.location 未定义的错误并且您无法进入该状态,那么您可以使用 withRouter 高阶组件包装 UnitOverview 导出。

export default withRouter(UnitOverview);