Is there a best way to go about using .map() to output elements with refs?
I'm doing this so I can track the elements (generated from state) for collision detection in an endless runner style game (without canvas).
I've tried 3 different approaches and matter what I do I seem to get ref=ref()
when it should be ref=“tango”
(as per the state). Image here - 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.
Code being used-
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>
)}
The above use a function to generate dom, but this also happens if outputting inline html and when using a component.
Any help would be greatly appreciated! 😀
Define a function for a ref
and store the refs in the class variable object like
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>
);
}
You can read more about Refs and Dom Here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.