首先,我将向您展示我的代码,然后解释我要实现的目标。
Class SectionHues extends React.Component {
handleClick = () => {
console.log(this.input.innerText);
}
render() {
return(
{Object.entries(this.props.colorChange).map(([colorName, colorHex]) => (
<div key={shortid.generate()} className="button-hues-container">
{/** On button click copy the span's innerText */}
<button onClick={this.handleClick} className="button-hues">
<span className="hues-info">
<span className="section-color-name">
{colorName}
</span>
{/** Need to copy the innerText of this span tag */}
<span ref={input => this.input = input} className="color-hex">
{colorHex.toLowerCase()}
</span>
{/** End copy */}
</span>
</button>
</div>
))}
)
}
}
您可以看到,按钮在数据库中循环,并使用其各自的文本创建多个按钮。我曾尝试使用ref
解决问题,但我做不到。单击任何按钮时,复制的文本都是相同的。有什么方法可以将按钮链接到id
,以便在单击按钮时仅复制相应的文本?如果您有不使用id
的替代方法,也可以使用。
只需将参数添加到handleClick
。
<button onClick={() => this.handleClick(colorHex.toLowerCase())}