有没有最好的方法来使用 .map() 输出带有 refs 的元素?
我这样做是为了在无尽的运行者风格游戏(无 Canvas )中跟踪元素(从状态生成)以进行碰撞检测。
我尝试了 3 种不同的方法,无论我做什么,我似乎都得到了 ref=ref()
而它应该是 ref=“tango”
(根据州)。图片在这里 - https://i.imgur.com/oeStcHb.png
EDIT: for others in future, I have since learned that
ref=ref()
is expected behaviour to indicate a callback is associated with it, instead of the old way of showing the actual ref.
正在使用的代码-
this.state = {
people: {
tango: { height: 10, weight: 200 },
cash: { height: 20, weight: 300 }
}
};
...
outputStatePeople(key) {
return(<span className="db" key={key} ref={key}>name: {key}</span>)
}
...
render() { return (
<div>
{Object.keys(this.state.people).map(key => this.outputStatePeople(key))}
</div>
)}
上面使用函数生成dom,但是输出内联html和使用组件时也会出现这种情况。
任何帮助将不胜感激! 😀
最佳答案
为 ref 定义一个 函数
并将 refs 存储在类变量对象中,例如
constructor(props) {
super(props);
this.state = {
people: {
tango: { height: 10, weight: 200 },
cash: { height: 20, weight: 300 }
}
};
this.domRefs = {};
}
outputStatePeople(key) {
return (
<span className="db" key={key} ref={(ref) => {this.domRefs[key] = ref}}>
name: {key}, height: {this.state.people[key].height}
</span>
);
}
您可以阅读更多关于 Refs 和 Dom 的信息 Here
关于javascript - 使用 .map() 生成带有 Refs 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49110992/