reactjs - 从父组件更改 react 钩子(Hook)状态

标签 reactjs react-hooks

我有一个像这样的钩子(Hook)组件:

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 Hook 来允许子级仅向父级公开特定属性

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"/>

关于reactjs - 从父组件更改 react 钩子(Hook)状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55889357/

相关文章:

reactjs - 如何制作一个 dist reactjs 应用程序?

javascript - 通过增加或减少输入框中的数量来更新糖果的总成本 - React JS

javascript - 我可以将 react-native-i18n 库与 react-native-web-boilerplate 一起使用吗

javascript - 设置状态不是在 React/ES6 中重新渲染组件

reactjs - 为什么 useEffect 钩子(Hook)不触发依赖项数组中的对象?

javascript - 我如何从react中的redux状态中提取数据

javascript - 为什么 componentDidMount 在 componentWillUnmount 之后运行?

reactjs - React 组件在状态更新时不渲染

javascript - 与 React hooks 的 setState 回调等效

javascript - Hook 状态落后于 prop 状态