如何在克隆元素上放置引用?

尼古拉斯

我有一个 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;

博詹德拉·劳尼亚尔

我不会完整地回答它。但只是想帮助你。这是我的另一篇文章,可以帮助您参考。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章