React Typescript:将函数作为 prop 传递给 child 并从 child 调用它

React Typescript: Passing function as prop to child and call it from the child

我需要将函数作为 prop 传递给 child,然后 child 需要调用它。

这是我的 parent:

interface DateValue {
  dateValue: string;
}

const Page: React.FC = () => {
    
  const dateChanged = (value: DateValue) => {
    console.log(value);
  }

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle>Financial Records</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent fullscreen>
        <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Financial Records</IonTitle>
          </IonToolbar>
        </IonHeader>
        <DateContainer onChanged={e => dateChanged} />
      </IonContent>
    </IonPage>
  );
};

export default Page;

这是我的 child:

interface Prop {
  onChanged: (date: string) => void
}

const DateContainer: React.FC<Prop> = (prop: Prop) => {

  const [currentDate, setCurrentDate] = useState<string>(moment().toISOString());
  const picker = createRef<HTMLIonDatetimeElement>();

  const dateChanged = (value: string) => {
    setCurrentDate(value);
    prop.onChanged(value);
  }

  const openPicker = () => {
    picker.current?.open();
  }

  return (
    <div className="DateContainer">
      <div className="header">
        <h3 className="title"><IonDatetime onIonChange={e => dateChanged(e.detail.value!)} ref={picker} value={currentDate} /> <IonIcon onClick={openPicker} className="icon" ios={calendarOutline} md={calendarSharp} /></h3>
      </div>
    </div>
  );
};

export default DateContainer;

当 child 从以下位置调用 prop.onChanged(value); 时:

const dateChanged =(值:字符串)=> { 设置当前日期(值); prop.onChanged(值); <-- 这里 }

它不调用:

const dateChanged = (value: DateValue) => {
    console.log(value);
}

来自parent.

我做错了什么?

您没有在父级中调用您的函数。像这样使用

<DateContainer onChanged={e => dateChanged(e)} />

或者

<DateContainer onChanged={dateChanged} />