简体   繁体   English

我如何从父母那里叫 function 中的孩子做出反应?

[英]How can i call a child inside function from parent in react?

i try to run child function in parent component.我尝试在父组件中运行子 function。

I have a two child component with different functions.我有两个具有不同功能的子组件。 if active prop is true i try to call childOneFunction, otherwise i should call childTwoFunction.如果 active prop 为真,我会尝试调用 childOneFunction,否则我应该调用 childTwoFunction。

Here is my example code.这是我的示例代码。 What is the best way to do that?最好的方法是什么?

const Parent = () => {
    const [active, setActive] = useState(true);
    function handleClickButton (){
        if(active){
            // call childOneFunction
        }else{
            // call childTwoFunction
        }
    }
    return (
      <div>
        <ChildOne active={active}/>
        <ChildTwo active={!active}/>
        <button onClick={handleClickButton}>Click</button>
      </div>
    );
  };

Child One component子一组件

  const ChildOne = () => {
    function childOneFunction() {
        return 'Child One Clicked'
      }
    return (
      <div>
        <h1>{childOneFunction}</h1>
      </div>
    );
  };

Child Two component子二组件

  const ChildTwo = () => {
    function childTwoFunction() {
        return 'Child Two Clicked'
      }
    return (
      <div>
        <h1>{childTwoFunction}</h1>
      </div>
    );
  };

you can use ref to call the functions of the child component from the parent component, here is the full example:您可以使用 ref 从父组件调用子组件的功能,这是完整的示例:

import React, { forwardRef, useRef, useImperativeHandle , useState} from 
 'react';
export default function ParentFunction() {
const child1Ref = useRef();
const child2Ref = useRef();
const [active, setActive] = useState(false);

const handleClick = (nm=1) =>{
  if(active){
    child1Ref.current.showAlert()
  }else{
    child2Ref.current.showAlert()
  }
}

return (
    <div className="container">
        <div>
            Parent Component
        </div>
        <button
            onClick={handleClick}
>
        Call Function
        </button>

        <Child1 ref={child1Ref} />
        <Child2 ref={child2Ref}  />
    </div>
)
}


const Child1 = forwardRef((props, ref) => {
useImperativeHandle(
    ref,
    () => ({
        showAlert() {
            alert("Child 1 Function Called")
        }
    }),
)
return (
   <div>Child Component 1</div>
)
})


const Child2 = forwardRef((props, ref) => {
useImperativeHandle(
  ref,
  () => ({
      showAlert() {
          alert("Child 2 Function Called")
      }
  }),
)
 return (
 <div>Child Component 2</div>
)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM