我已经开发一个项目三个月了。我需要从父组件(功能组件)中的子组件(基于类的组件)调用一个方法。我为此使用了 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 方法属于子组件。