【问题标题】:How to call a method from a component using Route in React Router v4?如何在 React Router v4 中使用 Route 从组件调用方法?
【发布时间】:2017-08-31 15:58:43
【问题描述】:

我有一些用 react router v4 编写的嵌套路由,在导航组件中我有一个输入框。

在提交时,我需要在不同的路线上调用一个方法(在着陆组件上)并传递值。我找不到任何在 Route 中调用方法的示例。

欢迎使用带有数据和不同路线的导航的任何其他方式/解决方法。

我的路线:

 return (
        <div>
            <Navigation callSearch = {this.callSearch.bind(this)} />
            <Switch>

                <Route path="/u/:slug" component={AuthorPage}/>
                <Route path="/:location/:slug" component={PhotoDetails}/>
                <Route path="/" component={Landing} />
            </Switch>
        </div>
    )

在导航中我调用 callSearch() :

   searchPhotos(e) {
    e.preventDefault();

    if(this.state.searchTerm) {
        this.props.callSearch(this.state.searchTerm);
    }
}

【问题讨论】:

  • 使用 redux 作为状态管理器

标签: reactjs react-router react-router-v4


【解决方案1】:

我已使用来自react-router 模块的withRouter 在我的应用程序中解决了这个问题。

            import { Route } from "react-router-dom";
            import { withRouter } from "react-router";

            class SideBar extends Component {


            callSearch = (searchKeyword) => {

                if(searchKeyword)  this.props.history.push(`/u/${searchKeyword}`);

            };

            render() {
                return (
                    <div>
                        <Navigation callSearch = {this.callSearch} />
                        <Switch>

                            <Route path="/u/:slug" component={AuthorPage}/>
                            <Route path="/:location/:slug" component={PhotoDetails}/>
                            <Route path="/" component={Landing} />
                        </Switch>
                    </div>
                )
            }


            export default withRouter(SideBar);

希望这对其他人有帮助!!!

【讨论】:

    猜你喜欢
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2017-05-16
    • 2019-12-30
    • 2018-07-16
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多