0

我已经开发一个项目三个月了。我需要从父组件(功能组件)中的子组件(基于类的组件)调用一个方法。我为此使用了 ref ,但它没有用。这是父组件:

import React, { useState, useEffect, useRef, createRef } from "react";
import CityPicker from "../../components/public/cityPicker";
import Chip from "../../components/forms/chip";
import Sidebar from "./sidebar";

import { Router } from "../../routes";
import NextRouter, { withRouter } from "next/router";

const Search = props => {
  const [filterItem, setFilterItem] = useState();

  const deleteFilterItem = createRef();

  const deleteChipHandler = event => {
    filterItem
      ? deleteFilterItem.current.onDeleteSearchableFilterItem(
          event,
          "stateOrProvince",
          "selectedStateOrProvince"
        )
      : "";
  };

  return (
    <>
      <div className={filterItem ? "filters-display" : ""}>
        {filterItem
          ? filterItem.map((item, index) => {
              return (
                <Chip
                  id={item.id}
                  key={index + "selected city"}
                  label={item.value}
                  onDelete={e => deleteChipHandler(e)}
                />
              );
            })
          : ""}
      </div>

      <Sidebar ref={deleteFilterItem} />
    </>
  );
};

export default withRouter(Search);

onDeleteSearchableFilterItem 方法属于子组件。

4

1 回答 1

0

在您的子组件中编写这样的函数。data是您从该组件的状态中获得的数据,或者是您使用 redux 时从 reducer 获得的状态(如 this.props.data):

 const onDelete = () => {
    this.props.onDelete(data);
    }

然后在父级中调用它:

import { Router } from "../../routes";
import NextRouter, { withRouter } from "next/router";

const Search = props => {
  const [filterItem, setFilterItem] = useState();

  const deleteFilterItem = createRef();

  const deleteChipHandler = (event, data) => {
    filterItem
      ? deleteFilterItem.current.onDeleteSearchableFilterItem(
          event,
          data
        )
      : null;
  };

  return (
    <>
      <div className={filterItem ? "filters-display" : ""}>
        {filterItem
          ? filterItem.map((item, index) => {
              return (
                <Chip
                  id={item.id}
                  key={index + "selected city"}
                  label={item.value}
                  onDelete={deleteChipHandler}
                />
              );
            })
          : ""}
      </div>

      <Sidebar ref={deleteFilterItem} />
    </>
  );
};

export default withRouter(Search);
于 2019-12-25T13:44:14.510 回答