2016-08-01 24 views
10

React-Router "withRouter"コンポーネントでES6 extend機能を使用する方法はありますか?React-Router HOC/withRouterのES6構文はありますか?

import { withRouter } from 'react-router'; 

export default class extends withRouter { 
    ... 
    //Use react router history prop to navigate back a page. 
    handleSomeEvent() { 
    this.props.router.goBack(); 
    } 
    ... 
} 

または私は昔の構図パターンを使用して立ち往生しています。このような

何か?

var MyComponent = React.createClass({ 
    ... 
}); 
export default withRouter(MyComponent); 

答えて

12

を含めなければならないだろう、(一例に過ぎ...部品が実装された後、あなたが2Sをリダイレクトする必要があります言っていない)怒鳴る参照してください。

ところで反応し、ルータの私のバージョンは、私は、これはこれまでのところ最も近い推測2.6(2.4+ withRouterに必要)

import React, { Component } from 'react'; 
import { withRouter } from 'react-router'; 

class MyComponent extends Component { 
    componentDidMount() { 
     setTimeout(() => { 
      this.props.router.push('my-url') 
     }, 2000); 
    } 

    render() { 
     return (
      <div>My Component</div> 
     ); 
    } 
} 

export default withRouter(MyComponent); 
+0

です。名前付きクラスと一緒にコンポジションを使うことは考えていませんでした。私は 'class MyComponent extends withRouter'を望んでいましたが、これは今のところできると思います。 –

+0

それは狂って見えるかもしれませんが、正常に動作します。私はreduxと "許可コントローラ"高次コンポーネントとの組み合わせでも使用します。 'export default connect(mapStateToProps、{fetchCampaigns})(AuthorizedComponent(Campaigns));' –

+0

@MarekJalovecコメント内のあなたの例では、あなたは屋根裏に置いてくれますか?それはありますか? 'export default connect(mapStateToProps、{fetchCampaigns})(AuthorizedComponent(withRouter(Campaigns))); –

3

このように使用できます。

@withRouter 
export default class extends withRouter { 
    ... 
    //Use react router history prop to navigate back a page. 
    handleSomeEvent() { 
    this.props.router.goBack(); 
    } 
    ... 
} 

しかし、あなたははい、それは簡単ですbabel-plugin-transform-decorators-legacy

関連する問題