我有通过反应编写的应用程序:
主要应用程序是:
function App({articles}) {
...
const SortVote=()=>{
console.log(childRef.current);
console.log(Object.getOwnPropertyNames(childRef.current))
childRef.current.SortVote();
}
const [art, setArt]= useState(articles);
const childRef = useRef();
return (
<div className="App">
<h8k-navbar header={title}></h8k-navbar>
<div className="layout-row align-items-center justify-content-center my-20 navigation">
<label className="form-hint mb-0 text-uppercase font-weight-light">Sort By</label>
<button data-testid="most-upvoted-link" className="small" onClick={SortVote}>Most Upvoted</button>
</div>
<Articles articles={art} cRef={childRef}/>
</div>
);
}
儿童组件是:
function Articles({ articles, cRef }) {
const [arts, setArts] = useState(articles);
const sortVote = () => {
const result = articles.sort((a, b) => {
if (a.upvotes > b.upvotes) {
return -1;
}
if (a.upvotes < b.upvotes) {
return 1;
}
return 0;
});
setArts(result);
};
const sortDate = () => {
const result = articles.sort((a, b) => {
if (a.date > b.date) {
return -1;
}
if (a.date < b.date) {
return 1;
}
return 0;
});
setArts(result);
};
useImperativeHandle(cRef, () => ({
sortVote,
sortDate
}));
if (articles)
return (
<div className="card w-50 mx-auto">
<table>
<thead>
<tr>
<th>Title</th>
<th>Upvotes</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{arts.map((item, index) => (
<tr data-testid="article" key={index}>
<td data-testid="article-title">{item.title}</td>
<td data-testid="article-upvotes">{item.upvotes}</td>
<td data-testid="article-date">{item.date}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
我在子组件中使用 useImperativeHandle 并尝试在父组件中使用 'childRef.current.SortVote()' 来调用子组件函数。但是浏览器有错误:
childRef.current.SortVote is not a function
完整代码在:https ://stackblitz.com/edit/react-vy7df9
在 useImpertiveHandle 钩子中,SortVote 和 sortDate 已经定义了函数,但是为什么这里仍然报错 SortVote is not function?