[英]React - How can I set my parent state using child component, using function structures (not classes)
I'm trying to change the state of parent component using a button in my child component by passing a function "setName" to the child.我正在尝试通过将 function“setName”传递给子组件,使用子组件中的按钮更改父组件的 state。 I read a lot of examples but they seemed to all use classes, where I'm trying to use functions since the React doc on hooks seems to promote functions over class.
我阅读了很多示例,但它们似乎都使用类,我试图在其中使用函数,因为钩子上的 React 文档似乎比 class 提升了函数。
In my parent, I have在我的父母中,我有
let [Name, setName] = useState("John Doe");
And I pass the setName method by using JSX in my return statement:我在 return 语句中使用 JSX 传递 setName 方法:
<Child childSetName=({setName})/>
In my child component I have在我的子组件中,我有
export const Child = ({childSetName}) => {
return(
<a onDoubleClick={()=>{childSetName("Mary Ann")}}>
Click me
</a>
)}
I got a typeError: childSetNameis not a function.我得到一个 typeError: childSetNameis not a function。
I also read this popular question , but it uses class, not functions as all the hooks example from React docs are.我也读过这个流行的问题,但它使用 class,而不是像 React 文档中的所有钩子示例那样起作用。
How can I set my parent state using child component, both retain their function structures not classes.如何使用子组件设置我的父 state,两者都保留其 function 结构而不是类。
I think you have wrong syntax here我认为你在这里有错误的语法
<Child childSetName=({setName})/>
Should change like this应该这样改
<Child childSetName={setName}/>
and和
export const Child = ({childSetName}) => {
return(
<a onClick={()=>{childSetName("Mary Ann")}}>
Click me
</a>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.