简体   繁体   English

如何在 reactjs 中将参考从孩子传递给父母?

[英]How to pass refs from child to parent in reactjs?

I want to focus the input box in my child component as soon as it renders and hence I am trying to pass ref of the input box up to its parent, which has a modal.我想在我的子组件渲染后立即将输入框聚焦,因此我试图将输入框的 ref 传递给它的父组件,它有一个模态。 And I am trying to focus on the input on entering the modal.我正在尝试专注于输入模式的输入。 (using the onEntered prop of react-bootstrap modal) (使用 react-bootstrap modal 的 onEntered 属性)

What am I using to create a modal?我用什么来创建模态? -> react-bootstrap -> 反应引导

Parent Component's JSX:父组件的 JSX:

        <Modal
            show={props.isLoginModalOpen}
            onHide={props.toggleLoginModal}
            onEntered={() => {                 //<----- I plan to use onEntered to focus on
             this.mobileInput.focus();         //       the input element in child 
             }}
        >
            <Modal.Header closeButton>
                <Modal.Title></Modal.Title>
            </Modal.Header>
            <Modal.Body>
                    
                        <EnterMobileView />   // <------- Child Component 

            </Modal.Body>
        </Modal>


Child Component's JSX:子组件的 JSX:

<div>
            <Form>
                <div className='form-group'>
                    <input
                        type='number'
                        name='mobile'
                        placeholder='Phone Number'
                        className='form-control'
                        ref={(input) => (this.mobileInput = input)} // <---- I want to pass this
                    />                                              // ref up to the parent
                </div>
            </Form>
        </div>

Is this the correct way to do this?这是正确的方法吗? is there a better way?有没有更好的办法?

Please check this example.请检查这个例子。 Hope it helps you.希望它可以帮助你。

MyParent Component我的父组件

import React, {useRef} from "react";
import MyChild from "./MyChild";

export default function MyParent() {

    const inputRef = useRef();

    function handleClick(event) {
        inputRef.current.focus();
    }

    return(
        <div>
            <MyChild ref={inputRef}/>
            <button onClick={handleClick}>Focus on Child's Input</button>
        </div>
    );
}

MyChild Component MyChild 组件

import React from "react";

const MyChild = React.forwardRef((props, ref) => {

    return(
        <div>
            <input ref={ref}/>
        </div>
    );
});
export default MyChild;

Looks like you need a ref forwarding here: https://en.reactjs.org/docs/forwarding-refs.html看起来你需要一个参考转发: https://en.reactjs.org/docs/forwarding-refs.html

The idea is to create the constant that holds the ref in the parent component, then pass this constant as prop to the Child component, which will use attach it to whatever element you want.这个想法是在父组件中创建保存 ref 的常量,然后将此常量作为 prop 传递给子组件,子组件将使用将其附加到您想要的任何元素。

I you need more help to implement it, just let me know in a comment.我需要更多帮助来实现它,请在评论中告诉我。

Parent Component父组件

import React,{useRef} from "react";
import Child from "./Child";

const Parent = () => {
    
  const childRef = useRef();

  const handleColorChange = ()=>{
    console.log("changing color","event envoked from Child.js")
    childRef.current.style.color = "#00ff00"
  }

  return (
    <>
      <h3>Parent Component</h3>
      <h1 ref={childRef} >Change Text Color</h1>
      <h4>-----------------------------------------------------------</h4>
    <Child handleColorChange={handleColorChange} />
    </>
  );
};
export default Parent;

Child Component子组件

import React from "react";

const Child = ({handleColorChange}) => {

    console.log("rendereing child...........")

  return (
    <>
      <h3>Child Component</h3>
      <button 
        onClick={handleColorChange}
      >
        Change Color
      </button>
    </>
  );
};
export default Child;

We can invoke the click event from the child component by passing the handleColorChange() function as a prop & pass it into the onClick event of button of child component.我们可以通过将handleColorChange() function 作为道具传递给子组件来调用子组件的点击事件,并将其传递给子组件按钮的onClick 事件。

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

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