简体   繁体   English

React - 如何使用子组件设置我的父 state,使用 function 结构(不是类)

[英]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.

相关问题 在 React 中,父组件如何从响应中设置状态以及在子组件中执行的异步获取功能? - In React, how can a parent component set state from the response an async fetch function performed in a child component? 如何在 React 中从父 class 更新我的子组件 state? - How can I update my child component state from the parent class in React? 如何从子组件更新我的父 state? - How can I update my parent state from child component? 我可以在反应中使用 useEffect 钩子在孩子的父母中设置状态吗 - Can i set state in parent from child using useEffect hook in react 如何在 React 中从子组件设置父组件的特定 state? - How to set a particular state of a parent component from child component in React? 如何通过异步函数设置反应父组件状态,然后将此状态作为props传递给子组件? - how to set react parent component state by a async function and then pass this state to child as props? 调用子组件中的函数未在反应 js 中设置父状态 - call a function in child component not set parent state in react js 如何在React中将子组件移到新的父组件? - How can I move my child component to new parent in React? 如何从 React 中的父组件调用子 function - How can I call Child function from Parent Component in React 在 REACT.js 中,如何将状态从子组件传递到父组件作为道具 - In REACT.js how can I pass a state from child component up to Parent component as a prop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM