在ES6中使用history mixin?

时间:2015-11-29 16:34:48

标签: reactjs ecmascript-6

我有以下代码,如何重构mixin?我听说你可以使用this.context解决某些问题,但我不确定如何在这种情况下应用它。我不明白为什么ES6想要杀死mixins ......一些向后兼容性会很好。

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>
        )
    }
});

2 个答案:

答案 0 :(得分:0)

React路由器在History docs文件中有一个专门的部分,介绍了如何在课程中使用历史记录。

如果你看一下history mixin is implemented的方式,那么你会发现它只是一个从上下文中获取历史变量的包装器。

上课时,您可以自己动手。

DT[,Cohort:=do.call(paste,c(Map(paste,cols,.SD),list(sep=", "))),.SDcols=cols]

或者,您可以查看react-mixin,它提供了使用带有ES6类的mixin的接口。

import PropTypes from 'react-router';

var SearchGithub = React.createClass({
  handleSubmit() {
    // ...
    this.context.history.pushState(null, '/profile/' + username);
  }
});

SearchGithub.contextTypes = { history: PropTypes.history };

React的类接口有designed without mixins

,这是有充分理由的

答案 1 :(得分:0)

反应路由器人建议的另一种方法是使用 props

如果您不满意使用createClass为您的应用程序中的少数组件进行历史记录混合,请提供以下几种方法:

•将this.props.history从路径组件传递到需要它的组件。

其他选项之一是Dan Price的上述回应(这让我想知道:“使用上下文而不是道具有什么意义?”)

来源链接:https://github.com/rackt/react-router/blob/fe9358adc864c556afff6fd472476ab84ce2d7d9/docs/api/History.md#but-im-using-classes