ref
正如你们已经知道的,在一个循环中
设置为
class
通过
this
关键词。这意味着您正在设置多个
refs
一种解决方案(不是理想的解决方案)是对它们进行不同的命名,可能会为每一个添加键
ref={input => {
this[`textInput${i}`] = input;
}}
当你瞄准它的时候
onClick
的事件
Button
action={
<Button
inverted
color="blue"
icon="copy"
onClick={this.handleClick(i)}
>
Focus
</Button>
}
现在,click事件应该更改并接受
id
作为参数并触发相关
裁判
handleClick = (id) => (e) => {
this[`textInput${id}`].focus();
}
请注意,这是一个简单的解决方案,但不是理想的解决方案,因为我们在每个渲染上创建了一个新的函数实例,因此我们传递了一个新的道具,该道具可以中断react的扩散算法(更好、更
“反应很快”
下一步)。
赞成的意见:
欺骗:
Working example
以下是完整代码:
class Services extends React.Component {
handleFocus(event) {
event.target.select();
}
handleClick = id => e => {
this[`textInput${id}`].focus();
};
render() {
return (
<div>
{sources.map((el, i) => (
<List.Item key={i}>
<Segment style={{ marginTop: "0.5em", marginBottom: "0.5em" }}>
<Input
fluid
type="text"
onFocus={this.handleFocus}
ref={input => {
this[`textInput${i}`] = input;
}}
value="text to copy"
action={
<Button
inverted
color="blue"
icon="copy"
onClick={this.handleClick(i)}
>
Focus
</Button>
}
/>
</Segment>
</List.Item>
))}
</div>
);
}
}
render(<Services />, document.getElementById("root"));
更好、更多
解决方案是使用组件组合或包装
并注入一些简单的逻辑,比如传递
而不是在父级中使用2个函数。
赞成的意见:
-
如前所述,性能问题的可能性较小
-
您可以重用此组件和逻辑
-
有时更容易调试
欺骗:
A working example
class MyButton extends React.Component {
handleClick = (e) => {
this.props.onClick(this.props.id)
}
render() {
return (
<Button
{...this.props}
onClick={this.handleClick}
>
{this.props.children}
</Button>
)
}
}
class Services extends React.Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleFocus(event) {
event.target.select();
}
handleClick(id){
this[`textInput${id}`].focus();
};
render() {
return (
<div>
{sources.map((el, i) => (
<List.Item key={i}>
<Segment style={{ marginTop: "0.5em", marginBottom: "0.5em" }}>
<Input
fluid
type="text"
onFocus={this.handleFocus}
ref={input => {
this[`textInput${i}`] = input;
}}
value="text to copy"
action={
<MyButton
inverted
color="blue"
icon="copy"
onClick={this.handleClick}
id={i}
>
Focus
</MyButton>
}
/>
</Segment>
</List.Item>
))}
</div>
);
}
}
render(<Services />, document.getElementById("root"));
编辑
作为编辑的后续内容:
但是当有多个卡片元素时,它仍然只适用于
发生这种情况的原因与之前相同,您使用的是相同的
i
对于两个阵列。
index
和
为了您的
姓名。
设置
姓名:
ref={input => { this[`textInput${index}${i}`] = input }}
将名称传递给处理程序:
<Button onClick={this.handleClick(`${index}${i}`)}></Button>
Working example
我修改了我的问题,并提供了第二个解决方案,这被认为是最佳实践。再读一遍我的答案,看看不同的方法。