如何在一个函数式的React组件中正确地读取URI参数?
在JavaScript中,如果该组件是Switch
的直接子元素,我们可以这样做:
function MyComponent(props) {
const query = props.location.search;
// ...
}
如果该组件不是 Switch
的直接子级,我们可以使用一个类:
class MyComponent extends Component<RouteComponentProps> {
render() {
const query = this.props.location.search;
// ...
}
}
export default withRouter(MyComponent);
在严格的 TypeScript 中如何使用函数式组件?
我们希望 location
属性(如果有其他属性也一样)能够被某个 interface
或 type
预定义并且由 React 提供,而不是组件的使用者提供。一个丑陋的方法是自己定义这个接口,然后期望它实际上就是这样。