最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass refs from child to parent in reactjs? - Stack Overflow

programmeradmin5浏览0评论

I want to focus the input box in my child ponent 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. And I am trying to focus on the input on entering the modal. (using the onEntered prop of react-bootstrap modal)

What am I using to create a modal? -> react-bootstrap

Parent Component's 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:

<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?

I want to focus the input box in my child ponent 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. And I am trying to focus on the input on entering the modal. (using the onEntered prop of react-bootstrap modal)

What am I using to create a modal? -> react-bootstrap

Parent Component's 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:

<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?

Share edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked May 18, 2020 at 20:43 Vikrant BhatVikrant Bhat 2,6384 gold badges18 silver badges33 bronze badges 2
  • Did you look at this question? – Józef Podlecki Commented May 18, 2020 at 20:51
  • @YevgenGorbunkov then how would I achieve focus on that input? – Vikrant Bhat Commented May 18, 2020 at 21:11
Add a ment  | 

3 Answers 3

Reset to default 3

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

import React from "react";

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

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

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 ponent by passing the handleColorChange() function as a prop & pass it into the onClick event of button of child ponent.

Looks like you need a ref forwarding here : https://en.reactjs/docs/forwarding-refs.html

The idea is to create the constant that holds the ref in the parent ponent, then pass this constant as prop to the Child ponent, which will use attach it to whatever element you want.

I you need more help to implement it, just let me know in a ment.

发布评论

评论列表(0)

  1. 暂无评论