在 React、Typescript 中获取查询参数

Get query parameters in React, Typescript

我有一个看起来像这样的组件:

class MyView extends React.Component<{}, {}> {
    render() {
        console.log((this.props as any).params); // prints empty object
        return (
            <div>Sample</div>
        );
    }
}

我想打印 URL 查询参数,但得到一个空对象。 (是的,我知道我将 {} 声明为 Props,但如果我不定义它,它就不会编译)。

有没有办法将 "default" 道具对象传递给我的组件,以便我可以访问 this.props.params?还是应该在 TypeScript 中以不同的方式完成?

要为组件分配默认属性,您应该使用 defaultProps:

class MyView extends React.Component<{}, {}> {
    render() {
        console.log((this.props as any).params); // prints empty object
        return (
            <div>Sample</div>
        );
    }
}

MyView.propTypes = {
  url: React.PropTypes.string
}

MyView.defaultProps = {
  url: ''
}

查看 the official docs 了解更多信息。

您需要定义 props 和 state 的类型,然后用它们代替 {}
不清楚你想从哪里得到 "URL query params",所以我就从 window.location 对象中取出它们:

interface MyViewProperties {
    params: string;
}

interface MyViewState {}

class MyView extends React.Component<MyViewProperties, MyViewState> {
    render() {
        console.log(this.props.params); // should print "param1=value1&param2=value2...."
        return (
            <div>Sample</div>
        );
    }
}

ReactDOM.render(<MyView props={ window.location.search.substring(1) } />, document.getElementById("container"));