【问题标题】:Link page bounded click handlers to Footer component将页面有界点击处理程序链接到页脚组件
【发布时间】:2017-12-12 10:36:15
【问题描述】:

Right now I have a Footer component with three different buttons. 其中两个按钮的 onClick 取决于页面,并在这些页面中定义。目前我在Page组件中单独渲染Footer组件,其中onClick函数被定义并作为道具传递,并且效果很好。

但是我在页面中添加了 CSS 元素 max-width,并且也影响了页脚,这是我不想要的。

为了解决这个问题,我需要在页面组件之外和路由器组件中呈现页脚,就像页眉一样。但问题是我不知道如何链接页面组件中定义的这两个页脚按钮的点击处理程序。

解决此问题的最佳方法是什么?在我的 Redux 商店中推送 onClick 函数?


目前它是这样工作的:

Router.js

<div id="router-container">
    <Header />

    <Switch>
        <Route path="/dashboard" component={DashboardPage} />
        <Route path="/settings" component={SettingsPage} />
    </Switch>
</div>

DashboardPage.js

const DashboardPage = () => (
    <div id="dashboard-page">
        ...content
        <Footer onRightButtonClick={myDashboardPageClickHandler} />
    </div>
);

SettingsPage.js

const SettingsPage = () => (
    <div id="settings-page">
        ...content
        <Footer onRightButtonClick={mySettingsPageClickHandler} />
    </div>
);

但是我怎样才能让它像这样工作:

Router.js(新)

<div id="router-container">
    <Header />

    <Switch>
        <Route path="/dashboard" component={DashboardPage} />
        <Route path="/settings" component={SettingsPage} />
    </Switch>

    <Footer />
</div>

DashboardPage.js / SettingsPage.js

const DashboardPage = () => {

    // set the onClick of the footer somehow to myDashboardPageClickHandler()

    return (
        <div id="dashboard-page">
            ...content
        </div>
    );
};

【问题讨论】:

  • 可以分享myDashboardPageClickHandler函数的代码吗?
  • 当然。 const myDashboardPageClickHandler = selectedTargetIndex &gt; 0 ? decrementSelectedTargetIndex : 'disable';。它检查一个值并返回一个 Redux 操作或定义按钮应该被禁用的字符串。

标签: reactjs redux react-router react-redux


【解决方案1】:

我建议使用 React Router 的 withRouter 函数来转换 Footer,如下所示:

const FooterWithRouter = withRouter(Footer);

然后,在 Footer 组件中,定义如下函数:

handleRightButtonClick() {
  const pathname = { this.props.location };

  if ( pathname === '/dashboard' ) {
    return myDashboardPageClickHandler;
  } else if ( pathname === '/settings' ) {
    return mySettingsPageClickHandler;
  }
}

并将按钮的onClick赋值给这个函数的返回值,像这样:

<button class="right-arrow" onClick={handleRightButtonClick()}></button>

看看这是否有效。

【讨论】:

  • 感谢您的回答。然而,myDashboardPageClickHandlermySettingsPageClickHandler 函数没有定义。这些点击处理程序是在页面组件中定义的,而不是在路由器中。
  • @Potato 这些函数的功能是什么?我想这很常见,比如导航或某事?
  • @Potato 我看到你除了在这些函数中调度动作之外什么都不做,所以只需 import 那些动作创建者在这里,并解雇它们......即复制函数 myDashboardPageClickHandler 和 @ 的功能987654331@ 到 handleRightButtonClick 函数内部。我认为这样更清晰、更干净。
  • 乐于助人!也考虑支持接受的答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 2016-09-04
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多