更改父组件的Reaction挂钩状态 [英] Change react hook state from parent component

查看:0
本文介绍了更改父组件的Reaction挂钩状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的钩子组件:

import React, { useState} from "react";

const MyComponent = props => {
  const [value, setValue] = useState(0);
  const cleanValue = () => {
    setValue(0);
  };

  return (<span><button onClick={()=>setValue(1)}/>{value}<span>)
}

我要重置父组件中的值。如何从父组件调用清洁值?父组件是有状态组件。

推荐答案

如果父组件必须控制子状态,则该状态可能必须驻留在父组件本身中。但是,您仍然可以使用ref从父级更新子状态,并在子级中公开一个重置方法。您可以使用useImperativeHandle挂钩来允许子级仅向父级公开特定属性

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="真">
const { useState, forwardRef, useRef, useImperativeHandle} = React;


const Parent = () => {
  const ref = useRef(null);
  return (
     <div>
      <MyComponent ref={ref} />
      <button onClick={() => {ref.current.cleanValue()}} type="button">Reset</button>
     </div>
  )
}

const MyComponent = forwardRef((props, ref) => {
  const [value, setValue] = useState(0);
  
   const cleanValue = () => {
    setValue(0);
  };

  useImperativeHandle(ref, () => {
     return {
      cleanValue: cleanValue
     }
  });

  return (<span><button type="button" onClick={()=>setValue(1)}>Increment</button>{value}</span>)
});
ReactDOM.render(<Parent />, document.getElementById('app'));
<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="app"/>

这篇关于更改父组件的Reaction挂钩状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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