我有以下代码,如何重构mixin?我听说你可以使用this.context绕过某些事情,但不确定它在这种情况下如何应用。我不明白ES6为什么要杀死Mixin。。。一些向后兼容性会很好。
import React from 'react';
import {Router, History} from 'react-router';
var SearchGithub = React.createClass({
mixins: [ History ], //not sure what to do with this
handleSubmit: function() {
var username = this.refs.username.value;
this.refs.username.value = '';
this.history.pushState(null, '/profile/'+username);
},
render: function() {
return (
<div className="col-sm-12">
<form onSubmit={this.handleSubmit}>
<div className="form-group col-sm-7">
<input type="text" className="form-control" ref="username" />
</div>
<div className="form-group col-sm-5">
<button type="submit" className="btn btn-block btn-primary">Search Github</button>
</div>
</form>
</div>
)
}
});
React路由器在History文档文件中有一个专门的部分,解释了如何将历史与类一起使用
若您观察一下历史mixin的实现方式,就会发现它只是一个从上下文获取历史变量的包装器。
有了你的课,你可以自己做。
import PropTypes from 'react-router';
var SearchGithub = React.createClass({
handleSubmit() {
// ...
this.context.history.pushState(null, '/profile/' + username);
}
});
SearchGithub.contextTypes = { history: PropTypes.history };
或者,您可以看看react mixin,它为使用带有ES6类的mixin提供了一个接口。
import { History } from 'react-router';
import reactMixin from 'react-mixin';
var SearchGithub = React.createClass({
// ...
});
reactMixin(SearchGitHub.prototype, History);
React的类接口是在没有mixin的情况下设计的,这是有充分理由的。
react路由器人员建议的另一种方法是使用道具:
如果你不喜欢为了History mixin而为应用程序中的少数组件使用createClass,那么有几个选项:
•将此.props.history从您的路由组件传递到需要它的组件。
另一个选择是Dan Price上面的回应(这让我想知道:"使用上下文而不是道具有什么意义?")
源链接:https://github.com/rackt/react-router/blob/fe9358adc864c556afff6fd472476ab84ce2d7d9/docs/api/History.md#but-im使用类