简体   繁体   English

从父组件访问子组件引用

[英]Access Child component reference from Parent Component

I am new to react and I am trying to access a child component reference from a callback method in the parent component.我是新手,我试图从父组件中的回调方法访问子组件引用。 When I try to access the reference, I am seeing the reference as null.当我尝试访问引用时,我看到引用为空。

Parent Component父组件

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import ChildComponentA from '../ChildComponentA';
import ChildComponentB from '../ChildComponentB’;

export default function ParentComponent(props) {

 const calendarRef = React.createRef();

const handleYearClick = (value) => {
    // const ref = React.createRef();
    console.log('click:', value, calendarRef);
    // setSelectedView('month');
    // const calendarApi = calendarRef.current.getApi();
};
const handleFilterEvent = (value) => {
const calendarApi = calendarRef.current.getApi();
if (value.includes('next')) calendarApi.next();
if (value.includes('prev')) calendarApi.prev();
}

return (

<section>

<ChildComponentA
    defaultView="dayGridMonth"
    eventData={allEvents}
    calendarRef={calendarRef}
     currentLang={currentLang}
/>
<ChildComponentB
 legendLabels={calendarLabels}
 currentYear={currentYear}
 yearEvents={allEvents}
onClick={handleYearClick}

/>
<ChildComponentC
 onClick={handleFilterEvent}
disableNextButton={disableNextButton}
disablePrevButton={disablePrevButton}

/>

<section/>
);

I am using the full calendar libary inside my ChildComponentA and I am trying to access the calendar Api from the parent.我在我的 ChildComponentA 中使用完整的日历库,我试图从父级访问日历 Api。

The code in my child component A is,我的子组件 A 中的代码是,

export default function ChildComponentA(props) {
const {
    eventData,
    defaultView,
    calendarRef,
    currentLang,
  } = props;
  return (
    <section className={rootClass}>
      <FullCalendar
        ref={calendarRef}
        plugins={[dayGridPlugin]}
        initialView={defaultView}
        nowIndicator
        editable
        headerToolbar={false}
        weekNumbers
        contentHeight="auto"
        events={eventList}
        dayMaxEventRows
        views={eventTimeGrid}
        eventOrder="-start"
        eventClick={(event) => handleEventClick(event.event)}
        locale={currentLang}
      />
</section>
);

}

EDITED: Adding ChildComponentB code,编辑:添加 ChildComponentB 代码,

export default function ChildComponentB(props) {

const MONTHNAMES = ['January', 'February', 'March', 'April', 'May', 'June','July', 'August', 'September', 'October', 'November', 'December',];

const customDayClick = (date, events) => {
    if (date) {
      const yearNum = moment(date.date).month();
      const month = MONTHNAMES[yearNum];
      const goToDate = `${currentYear}-${month}-01`;
      onClick(goToDate);
    }
    if (events) {
      console.log('events:', events);
    }

    return null;
  };


return (
    <>
      <section className={rootClass}>
        <Calender
          id="yearCalendar"
          allowOverlap
          displayHeader={false}
          dataSource={eventDataSource}
          displayWeekNumber={false}          
          onDayClick={customDayClick}
          year={currentYear}
          language={currentLang}
        />
);
}

When I console log calendarRef inside handleYearClick in the parentComponent, I see it as null .当我在 parentComponent 的 handleYearClick 内控制台 log calendarRef 时,我将其视为 null 。 ({current: null} current: null). ({当前:空}当前:空)。 But when I try the same inside the handleFilterEvent method which is a callback from ChildComponentC, I see the reference of full calendar like this {current: FullCalendar}.但是,当我在作为 ChildComponentC 回调的 handleFilterEvent 方法中尝试相同操作时,我看到了像 {current: FullCalendar} 这样的完整日历的引用。 How do I get the reference of FullCalendar inside handleYearClick.如何在 handleYearClick 中获取 FullCalendar 的引用。 What am i missing ?我错过了什么? It would be great if some one can help me resolve this.如果有人能帮我解决这个问题,那就太好了。 Thank you in advance.先感谢您。

So you can just pass the handleYearClick to the child component.所以你可以将handleYearClick传递给子组件。

export default function ParentComponent(props) {

    const handleYearClick = (date) => {
        console.log('Want to go to date:', date);
    };

    return ( <ChildComponentB [...] onClick={handleYearClick} /> );
}
function ChildComponentB({handleYearClick}) {

    const customDayClick = (date, events) => {
        if (date) {
            const goTo = moment(date.date).format('YYYY-MMMM-01');
            handleYearClick(goTo);
        }
    };


    return ( <Calender onDayClick={customDayClick} [...] /> );
}

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

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