简体   繁体   中英

How can I put a ref on a cloned element?

I have a Input component which takes an <input> element and renders it. It is a div, containing a label and an input.

My boss asked me that when I click anywhere in the div, it focuses on the input (so if it's a dropdown, it opens the dropdown, input, we can start writing text, etc).

I was thinking of doing it using refs: when an user clicks on the div, an onClick element is trigerred and the input gets focuses.

However, all the input are in this.props.children . How can I put a ref on the input and use it in my code? Here's what it looks like:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tooltip } from '@material-ui/core';

export class Input extends Component {
  displayTitle () {
    if (this.props.tip) {
      return (
        <label htmlFor={this.props.name} className="lone-input-container-title">
          {this.props.title}<Tooltip placement="top" arrow title={this.props.tip}><span className="shadow-md p-1 text-hardbacon rounded-full px-2 cursor-pointer ml-2">?</span></Tooltip>
        </label>);
    }
    return (
      <label htmlFor={this.props.name} className="lone-input-container-title">
        {this.props.title}
      </label>
    );
  }

  render () {
    return (
      <div className="lone-input-container">
        {this.displayTitle()}
        <div>
          {React.cloneElement(this.props.children[0])}
        </div>
      </div>
    );
  }
}

Input.propTypes = {
  name: PropTypes.string,
  title: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired,
  tip: PropTypes.string
};

export default Input;

I am not going to answer it in full. But just going to help you out. Here's my another post that could help you for reference.

And to use ref in cloned element, you can do like:

{React.cloneElement(this.props.children[0], {ref: this.refElement})}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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