我收到此警告:
警告:BackButton:上下文router
的类型说明无效;类型检查器函数必须返回null
或Error
,但返回一个布尔值。您可能忘记将参数传递给类型检查器创建器(arrayOf,instanceOf,objectOf,oneOf,oneOfType和shape都需要参数)。
这是我的代码(我想重用的BackButton组件)
import React, { Component } from "react";
import { Button } from 'antd';
class BackButton extends Component {
static contextTypes = {
router: () => true,
}
render() {
return (
<Button
onClick={this.context.router.history.goBack}>
Back
</Button>
)
}
}
export default BackButton;
如果可能,我最好使用PropTypes,但我不知道如何......
答案 0 :(得分:1)
您的propTypes示例:
import React, { Component } from "react";
import { Button } from 'antd';
import PropTypes from 'prop-types'; // You need to add this dependency
class BackButton extends Component {
static contextTypes = {
router: PropTypes.object
}
render() {
return (
<Button
onClick={this.context.router.history.goBack}>
Back
</Button>
)
}
}
export default BackButton;
您可以在此处详细了解propTypes:https://reactjs.org/docs/typechecking-with-proptypes.html。
答案 1 :(得分:1)
路由器的contextTypes
需要定义为PropTypes.object.isRequired
,首先使用
prop-type
npm install -S prop-types
并将其导入为
import PropTypes from 'prop-types'
并将上下文定义为
static contextTypes = {
router: PropTypes.object.isRequired
}
所以你的代码看起来像
import PropTypes from 'prop-types'
class BackButton extends Component {
static contextTypes = {
router: PropTypes.object.isRequired
}
render() {
return (
<Button
onClick={this.context.router.history.goBack}>
Back
</Button>
)
}
}