类内
constructor(props, context) {
super(props, context);
someFn = () = {
this.context.router.transitionTo('google.com');
}
在组件底部
MyComponent.contextTypes = {
router: React.PropTypes.func.isRequired
};
我不断收到错误警告:失败的上下文类型:所需的上下文路由器
未在主页
中指定。
当我单击按钮进行导航时,出现以下附加错误Uncaught TypeError:无法读取未定义的属性transitionTo
我什至尝试在构造函数中添加以下内容但无济于事
this.context = context
最佳答案
绝大多数应用程序不需要使用上下文。 (引用:https://reactjs.org/docs/context.html)
以下内容应该对您有帮助=>
import {Component} from 'react';
import PropTypes from 'prop-types';
class MyComponent extends Component {
static contextTypes = {
router: PropTypes.object
};
onFormSubmit() {
this.context.router.push('/home');
}
render() {
return (
<form onSubmit={this.onFormSubmit.bind(this)}>
</form>
);
}
}
关于javascript - React ES6 类转换不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803462/