Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs props.callback不是一个函数_Reactjs_React Hooks - Fatal编程技术网

Reactjs props.callback不是一个函数

Reactjs props.callback不是一个函数,reactjs,react-hooks,Reactjs,React Hooks,我希望从子组件触发父方法的执行 const ParentComponent: FunctionComponent = () => { const [detailsOpenState, setDetailsOpenState] = React. useState('hidden'); function myCallbackMethod() { setDetailsOpenState('displayed'); } return ( <TableBody&g

我希望从子组件触发父方法的执行

const ParentComponent: FunctionComponent = () => {

 const [detailsOpenState, setDetailsOpenState] = React. useState('hidden');

 function myCallbackMethod() {
   setDetailsOpenState('displayed');
 }

 return (
     <TableBody>
        < ChildComponent callback = { myCallbackMethod } />
     </TableBody>
 );

}
我的回调函数没有从父组件传递。相反,我在
回调中得到一个未定义的对象。在这个定义中,我怎么说应该在这里调用父函数呢?

你能试试这个吗

const ChildComponent: FunctionComponent<Props> = ({irrelevantInterface, callback}) => {
  
  function openDetails() {
    callback();
  }

  return (
  ...
  <TableRow onClick={openDetails}>
    
  </TableRow>
  ...
  )
}
constchildcomponent:FunctionComponent=({irrelatenterface,callback})=>{
函数openDetails(){
回调();
}
返回(
...
...
)
}
此部分:
({irrelatenterface},props)=>
您将从父组件接收2个参数。第一个参数始终是props,您将第一个参数定义为
{irrelatenterface}
。这实际上是您的第一个参数,并从中提取
不相关的接口。传递给组件的第二个参数(您将其命名为
prop
)实际上用于定义函数组件,而此代码错误地将其命名为
props

所以我相信你要找的是这样的:
const-ChildComponent:FunctionComponent=(props)=>{
const-ChildComponent:FunctionComponent=({irrelatenterface,…props})=>{


通过这种方式,您可以访问
props.callback
没有问题。

props是功能组件的第一个参数。好的,我更改了它,现在我得到了一个错误:属性“callback”不存在于类型“PropsWithChildren”上。props
包含
callback
的定义。我们无法从您发布的内容中看到它@jonrsharpe抱歉,我是新手。你在说什么样的道具定义?它应该是什么样子的?类型,
FunctionComponent
-什么是道具?如果你希望有一个名为callback的道具,它应该在那里定义。我使用了你的第二个选项。我得到一个错误属性“props”在类型“PropsWith”上不存在孩子们的好吧,我认为
中的
道具是你自己定义的,如果你还没有定义,你需要定义它。比如:
const-ChildComponent:FunctionComponent-void}>=(道具)=>{
为了使此方法有效,从您的示例中,似乎您正在将一个无效函数传递到回调中,因此在调用它时不会执行任何操作。我需要回调来指向父方法中的函数调用:
。我需要在callback()时执行myCallbackMethod是调用的。你知道如何实现吗?不。我使用的类型没有说
什么都不会执行
,它说
回调是一种函数类型,调用时没有参数,并且不需要返回值
。阅读此处了解更多信息:谢谢。我遇到了一个错误,我得到的错误属性“props”在类型“Pro”上不存在psWithChildren's
interface Props  {
  irrelevantInterface: bla_blabla;
  callback: any; 
}
const ChildComponent: FunctionComponent<Props> = ({irrelevantInterface, callback}) => {
  
  function openDetails() {
    callback();
  }

  return (
  ...
  <TableRow onClick={openDetails}>
    
  </TableRow>
  ...
  )
}