简体   繁体   English

使用组件外部组件的功能做出反应?

[英]Using the component's function outside of the component in react?

const DayScaleCell = props => (
    <WeekView.DayScaleCell
      {...props}
      onClick={() => Calendar.changeCurrDate(props.startDate)}
    />
  );

class Calendar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userId: fire.auth().currentUser.uid,
            data: appointments,
            currentDate: new Date(), // set to today's date by default
            message: '',
            open: false,
            selectedDate: new Date(),
        };
    }


    changeCurrDate = (date) => {
        this.setState({
            currentDate: date.getDate(),
        })
    }

    ....

The const DayScaleCell overrides an element in an external component that I am using in the Calendar component. const DayScaleCell覆盖我在Calendar组件中使用的外部组件中的元素。 I am trying to change a state when I click that element when it is clicked. 当我点击它时单击该元素时,我正在尝试更改状态。

https://codesandbox.io/s/llqmkq887 https://codesandbox.io/s/llqmkq887

This is the demo that I followed, and the demo console.log s the date clicked. 这是我遵循的演示,演示console.log是单击的日期。 I was trying the get the date of the clicked date (eg 19) and assign it to the currentDate state in my component. 我正在尝试获取点击日期的日期(例如19)并将其分配给我的组件中的currentDate状态。

However, my way gives me an error TypeError: Calendar.changeCurrDate is not a function . 但是,我的方式给了我一个错误TypeError: Calendar.changeCurrDate is not a function What would be a way to do this? 怎么办呢?

What you can do is to write DayScaleCell in some sort of high order function. 你可以做的是在某种高阶函数中编写DayScaleCell That will accept additional data, and then returns component itself 这将接受其他数据,然后返回组件本身

const getDayScaleCellComponent = onCellClick => props => (
  <WeekView.DayScaleCell
    {...props}
    onClick={() => onCellClick(props.startDate)}
  />
);

Using it in Calendar component Calendar组件中使用它

<WeekView
  startDayHour={9}
  endDayHour={19}
  dayScaleCellComponent={getDayScaleCellComponent(this.changeCurrDate)}
/>

Here is an example of how to pass a function to that component. 以下是如何将函数传递给该组件的示例。 https://codesandbox.io/s/189zv041n4 https://codesandbox.io/s/189zv041n4

The WeekView Component needed a change to allow for a function to be passed in WeekView组件需要进行更改以允许传入函数

 const DayScaleCell = (props, func) => (
     <WeekView.DayScaleCell {...props} onClick={() => func()} />
);

After that it is a simple matter of passing in the props and the function 在那之后,传递道具和功能是一件简单的事情

<WeekView
     startDayHour={9}
     endDayHour={19}
     dayScaleCellComponent={(e) => DayScaleCell(e, this.onChange)}
            />

The function that is being passed in increments the count state for the app class. 传递的函数会增加app类的计数状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM