【问题标题】:Access Child component reference from Parent Component从父组件访问子组件引用
【发布时间】:2020-11-01 23:36:29
【问题描述】:

我是新手,我正在尝试从父组件中的回调方法访问子组件引用。当我尝试访问引用时,我看到引用为空。

父组件

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/>
);

我在 ChildComponentA 中使用完整的日历库,并尝试从父级访问日历 Api。

我的子组件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>
);

}

已编辑:添加 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}
        />
);
}

当我在 parentComponent 中的 handleYearClick 内控制台记录 calendarRef 时,我将其视为 null 。 ({当前:空}当前:空)。但是,当我在作为 ChildComponentC 回调的 handleFilterEvent 方法中尝试相同的操作时,我会看到像 {current: FullCalendar} 这样的完整日历的引用。如何在 handleYearClick 中获取 FullCalendar 的引用。我错过了什么?如果有人可以帮助我解决这个问题,那就太好了。提前谢谢你。

【问题讨论】:

  • 请提供ChildComponentB 代码。但是 React 并没有建立在父母可以访问孩子的想法之上。事实上恰恰相反。父级可以将 data/fct 传递给可以使用的子级。
  • @farvilain 更新了子组件 B 的代码
  • 功能组件应该使用useRef钩子来创建react refs。 createRef 每次渲染都会创建一个新的引用,而 useRef 钩子通过重新渲染提供一个稳定的引用。您能否提供重现问题的组件的运行代码和框?

标签: javascript reactjs react-ref


【解决方案1】:

所以您可以将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} [...] /> );
}

【讨论】:

  • 不太明白。我们将什么从 handleYearClick methis 传递给组件 B?
  • 让B调用它
猜你喜欢
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
  • 2017-11-08
  • 2020-12-11
相关资源
最近更新 更多