[英]How can I put a ref on a cloned element?
我有一個 Input 組件,它接受一個<input>
元素並呈現它。 它是一個 div,包含一個 label 和一個輸入。
我的老板問我,當我單擊 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})}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.