簡體   English   中英

從父組件更改反應掛鈎狀態

[英]Change react hook state from parent component

我有一個這樣的鈎子組件:

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鈎子來允許子只向父公開特定屬性

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

從 React 文檔中關於Fully uncontrolled component with a key

為了重置值...,我們可以使用名為key的特殊 React 屬性。 當一個key改變時, React 將創建一個新的組件實例而不是更新當前的實例 鍵通常用於動態列表,但在這里也很有用。

在這種情況下,我們可以使用一個簡單的計數器來指示在按下Reset按鈕后需要一個新的MyComponent實例:

 const { useState } = React; const Parent = () => { const [instanceKey, setInstanceKey] = useState(0) const handleReset = () => setInstanceKey(i => i + 1) return ( <div> <MyComponent key={instanceKey} /> <button onClick={handleReset} type="button">Reset</button> </div> ) } const MyComponent = () => { const [value, setValue] = useState(0) return ( <span> <button type="button" onClick={()=>setValue(v => v + 1)}>{value}</button> </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"/>

你不能/不應該。 使用鈎子而不是有狀態的類組件不會改變這樣一個事實,即如果您希望父級擁有狀態,則需要在父級中聲明狀態。

它應該看起來像這樣,具體取決於您何時要重置該值(這里我使用了另一個按鈕):

const MyButton = (props) = (
  // Whatever your button does, e.g. styling
  <span>
    <button {...props} />
  <span>
)


const Parent = props => {
  const [value, setValue] = useState(0);
  const cleanValue = () => setValue(0);
  return (
    <div>
      <MyButton onClick={() => setValue(1)}>
        {value}
      </MyButton>
      <button onClick={cleanValue}>
        Reset
      </button>
    </div>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM