如何通过React组件传递一个函数来实现父级和子级之间的数据共享?



我已经按照这个教程(https://www.freecodecamp.org/news/pass-data-between-components-in-react/)尽我所能,但我仍然有麻烦

我得到以下错误:

Uncaught TypeError: childToParent is not a function"

下面是父函数:

function App() {
const childToParent =(value) => {console.log(value)}
...
return (
...
<SelectHours value={state.selectedHour} childToParent={childToParent}></SelectHours>
...
)

和子函数:

export default function SelectHours(selectedHours, childToParent) {
....
return (
<Select
labelId="select-demo"
id='select-demo'
defaultValue=""
//onChange={event => handleChange(event.target.value, true)}
value={workHours[0] ? workHours[0] : ""}
>
{
workHours.map((value, index) => {
return (
<MenuItem
value={value ? value : ""}
key={index}
onClick={() => childToParent(value)}
>
{value}
</MenuItem>
)
})
}
</Select>
)
....
}

你需要加上花括号,这样react才能知道它是一个道具。

export default function SelectHours({selectedHours, childToParent}) {
....
return (
<Select
labelId="select-demo"
id='select-demo'
defaultValue=""
//onChange={event => handleChange(event.target.value, true)}
value={workHours[0] ? workHours[0] : ""}
>
{
workHours.map((value, index) => {
return (
<MenuItem
value={value ? value : ""}
key={index}
onClick={() => childToParent(value)}
>
{value}
</MenuItem>
)
})
}
</Select>
)
....
}

必须像这样销毁道具。

export default function SelectHours({selectedHours, childToParent})

或者使用像这样的道具

export default function SelectHours(props)
...
onClick={() => props.childToParent(value)}

阅读本文中的对象解构

https://dmitripavlutin.com/javascript-object-destructuring/

你需要在

里面有一个childtopparent的处理程序

function App() {
...
const childToParent =(value) => {console.log(value)}
return (
...
<SelectHours value={state.selectedHour} childToParent={childToParent}></SelectHours>
...
)

App组件

最新更新