在功能组件中反应 URI 参数 [英] React URI params in functional components

查看:48
本文介绍了在功能组件中反应 URI 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从功能性 React 组件读取 URI 参数的正确方法是什么?

在 JavaScript 中,如果组件是 Switch 的直接子组件,我们可以这样做:

In JavaScript, if the component is a direct child of a Switch, we could do:

function MyComponent(props) {
    const query = props.location.search;
    // ...
}

如果组件不是 Switch 的直接子代,我们可以使用类:

If the component is not a direct child of a Switch, we could use a class:

class MyComponent extends Component<RouteComponentProps> {
    render() {
        const query = this.props.location.search;
        // ...
    }
}

export default withRouter(MyComponent);

严格的 TypeScript 中的函数式组件怎么样?

我们希望 location 属性(以及任何其他属性,如果有更多)可用并由某些 interfacetype 预定义,但由 React 提供,而不是组件的用户.一个丑陋的黑客是自己定义接口,然后期望它实际上是那样的.

We want the location property (and any other, if there are more) to be available and predefined by some interface or type, but supplied by React, not the user of the component. An ugly hack would be to define the interface ourselves and then expect it to actually be that way.

推荐答案

如果你将你的组件(函数式或类)包装在 withRouter 中,你的 props 扩展了 react-router 的 RouteComponentProps,它可以正确设置,就像你一样在第二个例子中做了.要访问正确的参数,您必须像这样扩展道具:

If you wrap your component (functional or class) in withRouter, your props extend the RouteComponentProps from react-router, which can be corretly set up, just as you did in the seconds example. To access the correct params, you have to extend the props like this:

RouteComponentProps<{ id?: string; }>

这会让打字稿知道,你有一个带有字段 id 的匹配道具,这是可选的.您现在可以使用 props.match.params.id 类型安全地访问它们.您也可以扩展它,以适应您的其他参数.希望这可以帮助.快乐编码.

This will let typescript know, that you have a match props with an field id, which is optional. You can now access them type safe with props.match.params.id. You can also extend that, to fit your other parameters. Hope this helps. Happy coding.

这篇关于在功能组件中反应 URI 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆