如何将refs分配给多个组件 [英] How to assign refs to multiple components
问题描述
我正在使用React使用 array.map
呈现多个数据。
如何从列表中禁用单击的按钮?
I'm using React to render multiple data using array.map
.
How can disable the clicked button from the list?
这是我的代码:
onRunClick(act, e) {
this.refs.btn.setAttribute("disabled", true);
}
render () {
return (
<div>
{
this.state.acts.map((act) => {
let boundActRunClick = this.onRunClick.bind(this, act);
return (
<p key={act._id}>
Name: {act.name}, URL(s): {act.urls}
<button ref='btn' onClick={boundActRunClick}>Run</button>
</p>
)
})
}
</div>
);
}
}
使用 refs
不起作用......我认为由于有多个按钮,我无法添加状态。
Using refs
doesn't work ... I think that I can't add a state since there are multiple buttons.
推荐答案
您应该使用参考回调
而不是参考,并且是的,您需要多个参考,数组应该是好的
You should use ref callback
instead of ref and also yes you need multiple refs, an array should be good
根据文档:
React支持可以附加到任何
组件的特殊属性。 ref属性采用回调
函数,
回调
将在安装组件后立即执行
或unmounted。
React supports a special attribute that you can attach to any component. The ref attribute takes a
callback
function, and thecallback
will be executed immediately after the component is mounted or unmounted.
在HTML元素上使用ref属性时, ref回调
接收底层DOM元素作为参数。
When the ref attribute is used on an HTML element, the ref callback
receives the underlying DOM element as its argument.
ref callbacks
在 componentDidMount
或
componentDidUpdate
生命周期挂钩。
使用ref回调只是在类上设置一个属性是访问DOM元素的常见
模式。首选方法是在ref回调中设置
属性,如上例所示。甚至还有
更短的写作方式: ref = {input => this.textInput = input}。
Using the ref callback just to set a property on the class is a common
pattern for accessing DOM elements. The preferred way is to set the
property in the ref callback like in the above example. There is even
a shorter way to write it: ref={input => this.textInput = input}.
字符串引用是遗留的,并且根据 docs :
String refs are a legacy and and as per the docs:
旧版API:字符串参考
如果你之前使用过React,你可能熟悉一个旧的
API,其中ref属性是一个字符串,比如textInput,而DOM
节点是以的形式访问的。 refs.textInput
。我们建议反对它
,因为字符串引用有一些问题,被认为是遗留的,并且在未来的一个版本中可能会删除
。如果你是
目前使用this.refs.textInput
来访问refs
,我们建议
而是回调模式。
If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as
this.refs.textInput
. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you’re currently usingthis.refs.textInput
to accessrefs
, we recommend the callback pattern instead.
constructor() {
super();
this.btn = [];
}
onRunClick(act, index, e) {
this.btn[index].setAttribute("disabled", true);
}
render () {
return (
<div>
{
this.state.acts.map((act, index) => {
let boundActRunClick = this.onRunClick.bind(this, act, index);
return (
<p key={act._id}>
Name: {act.name}, URL(s): {act.urls}
<button ref={(ref) => this.btn[index] = ref} onClick={boundActRunClick}>Run</button>
</p>
)
})
}
</div>
);
}
这篇关于如何将refs分配给多个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!