Call child method from parent

前端 未结 16 2096
长发绾君心
长发绾君心 2020-11-21 22:23

I have two components.

  1. Parent component
  2. Child component

I was trying to call child\'s method from Parent, I tried this way but couldn\

16条回答
  •  一向
    一向 (楼主)
    2020-11-21 23:12

    We're happy with a custom hook we call useCounterKey. It just sets up a counterKey, or a key that counts up from zero. The function it returns resets the key (i.e. increment). (I believe this is the most idiomatic way in React to reset a component - just bump the key.)

    However this hook also works in any situation where you want to send a one-time message to the client to do something. E.g. we use it to focus a control in the child on a certain parent event - it just autofocuses anytime the key is updated. (If more props are needed they could be set prior to resetting the key so they're available when the event happens.)

    This method has a bit of a learning curve b/c it's not as straightforward as a typical event handler, but it seems the most idiomatic way to handle this in React that we've found (since keys already function this way). Def open to feedback on this method but it is working well!

    // Main helper hook:
    export function useCounterKey() {
      const [key, setKey] = useState(0);
      return [key, () => setKey(prev => prev + 1)] as const;
    }
    

    Sample usages:

    // Sample 1 - normal React, just reset a control by changing Key on demand
    function Sample1() {
      const [inputLineCounterKey, resetInputLine] = useCounterKey();
    
      return <>
        
        

    (Credit to Kent Dodds for the counterKey concept.)

提交回复
热议问题