【问题标题】:How can I put a ref on a cloned element?如何将 ref 放在克隆的元素上?
【发布时间】:2020-11-20 06:52:59
【问题描述】:

我有一个 Input 组件,它接受一个 <input> 元素并呈现它。它是一个 div,包含一个标签和一个输入。

我的老板问我,当我单击 div 中的任意位置时,它会专注于输入(所以如果是下拉菜单,它会打开下拉菜单,输入,我们可以开始编写文本等)。

我正在考虑使用 refs:当用户点击 div 时,触发 onClick 元素并且输入获得焦点。

但是,所有输入都在this.props.children 中。如何在输入上放置 ref 并在我的代码中使用它?这是它的样子:

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;

【问题讨论】:

  • @BhojendraRauniyar 不,我的问题是关于将 ref 放在克隆的元素上。感谢您尝试帮助我!

标签: javascript html reactjs


【解决方案1】:

我不会完整回答。但只是想帮你。这是我的another post,可以帮助你参考。

要在克隆元素中使用 ref,您可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 2013-01-26
    • 2012-05-19
    • 1970-01-01
    • 2020-04-23
    • 2016-02-01
    • 2012-04-11
    相关资源
    最近更新 更多