有没有办法使用 Hooks 将数据从孩子传递给父母? [英] Ist there a way to pass data from child to parent using Hooks?

查看:35
本文介绍了有没有办法使用 Hooks 将数据从孩子传递给父母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 React 的绝对新手,我想将数据从子组件传递到父组件.但是如果我寻找这个问题,我总能找到使用状态"和回调"函数的旧"方式.例如,参见这篇文章:https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17

As an absolute newbie to React, I'd like to pass data from a child to parent component. But if I look for this question, I always find the "old" way using "state" and "callback" functions. See for example this article: https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17

由于所有指南都使用传统方式,我很困惑,因为它们看起来与我所知道的大不相同.例如,我没有在构造函数中使用this.state",而是使用了 useState() 钩子.

Since all the guides use the traditional way, I'm very confused because they look so different from what I know. For example, instead of using "this.state" in the constructor, I use the useState() Hook.

有什么方法或者我看不到 Hook 可以将数据从子组件传递到父组件吗?

Is there any way or maybe Hook I don't see that makes it possible to pass data from a child to a parent component?

推荐答案

假设您有一个父组件应用程序,该应用程序具有处理作为子组件的表单的提交(可以是任何其他类型的逻辑)的逻辑应用程序.

Imagine that you have a parent component App that has the logic for handling the submit (could be any other kind of logic) of a form that is a child component of App.

ChildForm 有一个本地状态来存储它的 inputValue.

The ChildForm has a local state to store its inputValue.

当您单击提交函数时,它会从父应用程序调用一个函数 onSubmit 并传递它的 inputValue(您可以传递它的任何其他值)出现在组件内部)被处理和提交,在这个例子中.

When you click the submit function, it will call a function onSubmit from the parent App and it will pass along its inputValue (you can pass any other value that it's present inside the component) to be processed and submitted, in this example.

所以它的要点是:

  • 将一个函数作为props
  • 从父级发送给子级
  • 孩子将调用该函数发送一些数据作为参数
  • 该函数将处理数据并可以触发来自父级的某些操作,例如

见下面的片段:

function App() {
  
  function onSubmit(formState) {
    console.log('I will submit my ChildForm Input State: ' + formState);
  }
  
  return(
    <ChildForm
      onSubmit={onSubmit}
    />
  );
}

function ChildForm(props) {
  const [inputValue,setInputValue] = React.useState('');
  
  function onChange() {
    setInputValue(event.target.value);
  }
  
  return(
    <React.Fragment>
    <div>I am ChildForm</div>
    <input type='text' value={inputValue} onChange={onChange}/>
    <button onClick={()=>props.onSubmit(inputValue)}>Click to Submit through parent App</button>
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div> 

这篇关于有没有办法使用 Hooks 将数据从孩子传递给父母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆