【问题标题】:Route to new component with props on button click React使用按钮上的道具路由到新组件单击反应
【发布时间】:2021-03-09 02:19:06
【问题描述】:

单击按钮时,我需要将新道具传递给 UnitOverview 并转到链接“OeeUnitOverview”。当我去链接“OeeUnitOverview 到组件将自动加载。 我想打印 OeeUnitOverview 类中的 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;

【问题讨论】:

  • 向我们提供Minimal, Complete, and Reproducible 代码示例可能会有所帮助。正在使用什么导航/路由?您想通过导航发送哪些额外的道具?
  • 我要发送ID和姓名。

标签: reactjs button hyperlink routes components


【解决方案1】:

我猜你正在使用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);

【讨论】:

猜你喜欢
  • 2021-01-24
  • 2019-08-15
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 2019-03-02
  • 2020-07-07
相关资源
最近更新 更多