如何使用 Reactjs 将日历的日期状态发送到另一个日历?

How to send the date state of calendar to another calendar with Reactjs?

我有两个日历,比如Agenda,有一个图标日历按钮,当我点击它时,它会被重定向到另一个日历(Planning),这些日历是用react-big-calendar开发的,我希望当我在议程的 juin 17 - 23 周导航时单击图标日历,它将被重定向到计划的 juin 17 - 23

我的代码是:https://codesandbox.io/s/m7k904y3o8

我尝试用 getWeek() 发送日期,但它不起作用。

我该如何解决?

你应该使用一些状态管理库

我的第一个建议是使用 Redux,因为该库可以很好地处理这种情况。你想在不相关的组件之间传递一些数据。拥有一个状态对象在这里会很好地为您服务。

第二个 (easier/quicker) 选项是向父组件(这称为容器)添加一些状态管理。您可以将一些状态传递给每个子项以及可以从子项触发的 setter 函数。

您的 App 组件作为容器的示例

import React, { Component } from "react";
import autobind from 'autobind-decorator';
import { Route, Link, Switch, Redirect } from "react-router-dom";
import Agenda from "./Agenda";
import Planning from "./Planning";
class App extends Component {
  state = {selectedDate: Date.now()}

  @autobind
  setActiveDate (dateToSet) {
    this.setState({selectedDat: dateToSet});
  }
  /*---------------------------------------------------- Rendu -----------------------------------------------------------------*/
  render() {
    return (
      <div>
        <Switch>
          <Route exact path="/" render={(props) => <Agenda {...props} setActiveDate={setActiveDate} selectedDate={this.state.selectedDate} />} />
          <Route exact path="/planning" render={(props) => <Planning {...props} selectedDate={this.state.selectedDate} />}/>
        </Switch>
      </div>
    );
  }
}

export default App;

一些注意事项

  • 首先,您不希望您的主要应用程序组件以这种方式用作容器,因此请制作另一个组件来处理此状态管理
  • autobind 装饰器的使用是为了使它更容易编写,如果你愿意,你可以在构造函数中绑定你的函数
  • 这个组件只显示了故事的一半,另一半在你的子组件中,你需要从这里读取日期并触发子组件(议程)的功能setActiveDate

结论

此方法比 redux 实现更能污染您的组件。但它比完整的 redux 设置更快。试着记住 "Single responsibility principal"

您可以向 this.props.history.push 添加额外的数据,这些数据将在 Planning 组件的 location 属性中可用。例如,如果您想查看 1995 年 12 月 20 日所在的那一周:

// Agenda.js: Routing to "/planning"

this.props.history.push("/planning", { date: new Date(1994, 11, 19, 0, 0)})
// Planning.js

constructor(props) {
    super(props); //Important

    this.state({
        /* ... */
        dateWeek: this.props.location.state && this.props.location.state.date
    });
}

// Following is a fix or else you would not get next/previous week.

getThisWeek = (dateWeek) => {
    this.setState({ dateWeek });
}


我推荐的另外两个解决方案是 URL parameters and Query parameters