【发布时间】:2021-03-30 08:56:11
【问题描述】:
我正在构建一个反应原生应用程序。我有一个父组件和一个子组件。子组件有一个按钮,其事件处理程序位于父组件中。在事件处理程序结束时,我还必须更新子组件中的特定状态。所以出于这个原因,我在父组件中使用了useRef 钩子来创建子组件的引用。现在,事件处理函数看起来像这样
const handleJoin = async (community: TCommunity) => {
// ..........
childComponentRef.current.setIsDataManipulated(true);
// ..........
};
但我在setIsDataManipulated 中得到一条红色波浪线,当我将鼠标悬停在它上面时,会出现以下错误
Property 'setIsDataManipulated' does not exist on type 'FC<TChildrenProps>'
这一定是因为打字稿无法知道子组件具有我要更新的状态。目前,我只使用 props 类型而不是 state 类型来注释子组件。我在网上搜索过,发现在使用基于类的组件时,我可以传递第二个泛型类型如React.Component<TProps, TState> 来对props 和state 进行注释。但是我如何使用React.FC 这样做呢?
【问题讨论】:
-
我不确定
childComponentRef.current.setIsDataManipulated(true);是不是个好主意。我同意@T.J。克劳德,你最好把它当作道具:don't make it state in the child component, make it a prop
标签: reactjs typescript react-native