gpt4 book ai didi

javascript - 在 react 路由器中通过 Prop 传递功能

转载 作者:行者123 更新时间:2023-11-30 20:32:07 24 4
gpt4 key购买 nike

我知道如何在 react 路由器中传递 Prop ,例如 string 类型。但是当我尝试传递功能 Prop 时遇到问题。在我的子组件上,这个 Prop 是 "undefined"

我的链接示例:

<Link to={'/Content/' + this.props.index + '/' + this.props.decreaseIndexProject}>Page n°1</Link>

index 属性是一个数字,所以我可以在我的子组件上获取它,但不是 decreaseIndexProject 属性。

我使用 PropType :

NavBar.propTypes = {
indexProject: PropTypes.number,
decreaseIndexProject: PropTypes.func
};

我的路由器组件:

<Router>
<Switch>
<Route path="/Content/:index/:decrease" exact name="content" component={Content} />
</Switch>
</Router>

也许还有其他方法可以传递函数?感谢您的帮助。

最佳答案

您可以使用 Link like 将函数作为位置状态传递

<Link to={{
pathname: '/Content/' + this.props.index
state: {decrease: this.props.decreaseIndexProject}
}}>Page n°1</Link>

<Router>
<Switch>
<Route path="/Content/:index" exact name="content" component={Content} />
</Switch>
</Router>

现在 在 Content 中,您可以像 this.props.location.state.decrease 一样使用它

关于javascript - 在 react 路由器中通过 Prop 传递功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com