您应该使用
ref callback而不是ref,并且是的,您需要多个ref,一个数组应该很好
根据文档:
React支持可以附加到任何组件的特殊属性。ref属性具有一个
callback功能,并且在callback安装或卸载组件后立即执行。在HTML元素上使用ref属性时,会
ref callback接收基础DOM元素作为其参数。ref callbacks之前被调用componentDidMount或componentDidUpdate生命周期钩。仅使用ref回调在类上设置属性是访问DOM元素的常见模式。首选方法是像上面的示例一样在ref回调中设置属性。甚至有一种更短的编写方法:
ref={input=> this.textInput = input}.
字符串引用是旧版,并且根据 docs :
旧版API:字符串引用
如果您以前使用过React,那么您可能会熟悉一个较旧的API,其中ref属性是一个字符串,例如“
textInput”,并且DOM节点的访问方式是this.refs.textInput。我们不建议这样做,因为字符串引用存在一些问题,被认为是旧问题,并且很可能会在将来的发行版中删除。如果您当前正在使用this.refs.textInputaccessrefs,我们建议改用回调模式。
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> ); }


