在Reaction组件之间传递数据

Passing Data between react components(在Reaction组件之间传递数据)
本文介绍了在Reaction组件之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在试着做简单的日历。在我的日历中,我有日、日、月和月名组件,以及我在主日历上访问它的所有内容。初始加载时,它将显示当前月历。

现在,当我从月份名称组件中选择"月"时,希望传递给"月"组件,然后传递到"天"组件以呈现日期。

我尝试使用回调函数,但它对我没有帮助

整个反应组件都在这里https://stackblitz.com/edit/react-ts-z2278r

Day component

import * as moment from 'moment'
import * as React from 'react'

import { showComponent } from '../../../../models'
import { MonthNames } from './'
import styles from './Calendar.module.scss'

interface IDatePickerMonthsProps {
  changeMonthComponent: (showComponent: showComponent, monthNo: number) => void
}

interface IDatePickerMonthsState {
  dateObject: moment.Moment,
  monthNo?: number
}

export class DatePickerMonths extends React.Component<IDatePickerMonthsProps, IDatePickerMonthsState> {

  constructor(props: IDatePickerMonthsProps) {
    super(props)
    this.state = {
      dateObject: moment()
    }
  }

  public render() {
    const monthPicker =
      <div className="datepicker-days">
        <table className={styles.table}>
          <thead>
            <tr>
              <th><span className="ms-Icon ms-Icon--ChevronLeft" title="Previous Month" onClick={this.onPrev}></span></th>
              <th className={styles["picker-switch"]} data-action="pickerSwitch" colSpan={5} title="Select Month">
                {this.year()}
              </th>
              <th><span className="ms-Icon ms-Icon--ChevronRight" title="Next Month" onClick={this.onNext}></span></th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td colSpan={7}>
                <MonthNames changeMonthComponent={() => this.showDays(this.state.monthNo)} />
              </td>
            </tr>
          </tbody>
        </table>
      </div>

    return (monthPicker)
  }

  private year = () => {
    return this.state.dateObject.format("Y");
  };

  private onPrev = () => {
    this.setState({
      dateObject: this.state.dateObject.subtract(1, "year")
    });
  };
  private onNext = () => {
    this.setState({
      dateObject: this.state.dateObject.add(1, "year")
    });
  };

  private showDays = (monthNo: number) => {
    console.log(monthNo)
    this.setState({ monthNo: monthNo })
    this.props.changeMonthComponent(showComponent.Days, monthNo)
  }
}

Month name component

import * as moment from 'moment'
import * as React from 'react'

import { showComponent } from '../../../../models'

interface IMonthNamesProps {
  changeMonthComponent: (showComponent: showComponent, monthNo: number) => void
}

export class MonthNames extends React.Component<IMonthNamesProps, {}> {
  private monthshort: string[] = moment.monthsShort();

  constructor(props: IMonthNamesProps) {
    super(props)
  }

  public render() {
    let monthshortname = this.monthshort.map((month, monthNo) => {
      return <span key={monthNo} onClick={() => this.showDays(monthNo)}>{month}</span>;
    });
    return monthshortname
  }

  private showDays = (monthNo: number) => {
    this.props.changeMonthComponent(showComponent.Days, monthNo)
  }
}

Month component

import * as moment from 'moment'
import * as React from 'react'

import { showComponent } from '../../../../models'
import { MonthNames } from './'
import styles from './Calendar.module.scss'

interface IDatePickerMonthsProps {
  changeMonthComponent: (showComponent: showComponent, monthNo: number) => void
}

interface IDatePickerMonthsState {
  dateObject: moment.Moment,
  monthNo?: number
}

export class DatePickerMonths extends React.Component<IDatePickerMonthsProps, IDatePickerMonthsState> {

  constructor(props: IDatePickerMonthsProps) {
    super(props)
    this.state = {
      dateObject: moment()
    }
  }

  public render() {
    const monthPicker =
      <div className="datepicker-days">
        <table className={styles.table}>
          <thead>
            <tr>
              <th><span className="ms-Icon ms-Icon--ChevronLeft" title="Previous Month" onClick={this.onPrev}></span></th>
              <th className={styles["picker-switch"]} data-action="pickerSwitch" colSpan={5} title="Select Month">
                {this.year()}
              </th>
              <th><span className="ms-Icon ms-Icon--ChevronRight" title="Next Month" onClick={this.onNext}></span></th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td colSpan={7}>
                <MonthNames changeMonthComponent={() => this.showDays(this.state.monthNo)} />
              </td>
            </tr>
          </tbody>
        </table>
      </div>

    return (monthPicker)
  }

  private year = () => {
    return this.state.dateObject.format("Y");
  };

  private onPrev = () => {
    this.setState({
      dateObject: this.state.dateObject.subtract(1, "year")
    });
  };
  private onNext = () => {
    this.setState({
      dateObject: this.state.dateObject.add(1, "year")
    });
  };

  private showDays = (monthNo: number) => {
    console.log(monthNo)
    this.setState({ monthNo: monthNo })
    this.props.changeMonthComponent(showComponent.Days, monthNo)
  }
}

推荐答案

我已经解决了我的问题,在**See Sharper**的帮助下,感谢支持和加票。

现在回到我的问题上。我的日历最初加载正确,但当我在MonthName组件(即,子组件)中更改月份和年份时,向上传递到DayPickerMonths(即父组件),然后向上传递到Calendar组件(即,祖父组件),然后向下传递到DatePickerDays组件(即,子组件与Calendar同级,与DayPickerMonths同级)

在视觉上看起来是这样的

因此从子(即MonthName)开始

函数

private showDays = (monthNo: number) => {
    this.props.changeMonthComponent(monthNo)
  }

调用渲染

public render() {
    let monthshortname = this.monthshort.map((month, monthNo) => {
      return <span key={monthNo} onClick={() => this.showDays(monthNo)}>{month}</span>;
    });
    return monthshortname
  }

DayPickerMonths(即父级)

<MonthNames changeMonthComponent={(monthNo) => this.showDays(monthNo, this.state.dateObject.year())} />

private showDays = (monthNo: number, year: number) => {
    this.props.changeMonthComponent(showComponent.Days, monthNo, year)
  }

日历(即祖父母)

<DatePickerMonths
              changeMonthComponent={(childData, monthNo, year) => this.changeMonthComponent(childData, monthNo, year)} />

private changeMonthComponent = (childData: showComponent, monthNo: number, year: number) => {
    this.setState({ showComponent: childData, monthNo: monthNo, year: year })
  }

DayPickerDays(即日历的子项和DayPicker的兄弟项)

private showMonths = () => {
    this.props.changeComponent(showComponent.Months)
  }
public componentDidMount() {
    this.setState({ dateObject: this.state.dateObject.month(this.props.monthNo).year(this.props.year) })
  }

我已在此更新了我的https://stackblitz.com/edit/react-ts-z2278r

但是,当在DayPickerDays组件中更改年份时,它没有反映在DayPickerMonths中,且传递数据很麻烦,我们应该使用反应上下文使其变得全局和简单。我会尽快更新这个答案,一旦我成为提供者,因为我需要为我的眼睛检查去预约医生

这篇关于在Reaction组件之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)