简体   繁体   English

当事件在父组件中触发时,将值从 React 子组件传递给父组件?

[英]Passing value from React child to parent component, when event is triggered in parent?

I know that 'passing value from child to parent' is a common question, but I can't find an answer to my particular case.我知道“将价值从孩子传递给父母”是一个常见问题,但我找不到针对我的特定情况的答案。

Basically, I have a parent component which has a list of children which have input values.基本上,我有一个父组件,它有一个包含输入值的子组件列表。

function Parent() {

    function submit() {
        // make some API call with the values from the children.   
    }

    return (
        <Child></Child>
        <Child></Child>
        ...
        <Button onClick={submit}>Submit</Button>
    )

}

function Child() {
    return (
        <TextField></TextField>
    )
}

I'm aware that you would normally pass a function as prop to the children.我知道你通常会将一个函数作为道具传递给孩子们。 That would work if the child knows when to call that function, but in this case the parent only knows because it has the button that triggers the event.如果孩子知道何时调用该函数,这将起作用,但在这种情况下,父母只知道因为它具有触发事件的按钮。

I could use an onChange event listener in the TextField inside the children, and constantly update the state in the parent whenever we change the text.我可以在子级内部的 TextField 中使用onChange事件侦听器,并在我们更改文本时不断更新父级中的状态。 But, this seems like a lot of complexity when I just want to get the values when we submit.但是,当我只想在提交时获取值时,这似乎很复杂。

If you don't want to use local state and onChange events (wich you said), you could use useRef and read the value directly.如果您不想使用本地状态和 onChange 事件(如您所说),您可以使用 useRef 并直接读取值。 Look at this example:看这个例子:

https://gist.github.com/jamesreggio/142215754ad06f375bd87657c6227ed8 https://gist.github.com/jamesreggio/142215754ad06f375bd87657c6227ed8

basically each of your child component would get ref wich it would forward to your input component, and then in submit you can directly access child value.基本上你的每个子组件都会得到 ref ,它会转发到你的输入组件,然后在提交中你可以直接访问子值。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM