javascript - 使用 .map() 生成带有 Refs 的元素

标签 javascript reactjs

有没有最好的方法来使用 .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/

相关文章:

javascript - 从子组件访问 onChange 事件 (React/Redux)

javascript - 类型错误 : state is not iterable on react and redux

javascript - 如何在创建新对象时应用条件检查并执行代码?

javascript - 如何根据类型字符串在 javascript 中创建新对象?

javascript - 如何使用 react-router 创建反向路由

javascript - 定价最小到最大下拉列表的相关下拉列表

javascript - 在加载内部 html 时显示图像

javascript - 动态渲染的标签总是小写

javascript - 在 React 中返回并渲染一个 div

javascript - 创建丰富的表单组件以向父组件公开值