[英]Accessing similar DOM elements
我目前正在开发一个组件,我需要访问每个<path>
节点。 我目前将其属性存储在一个数组中,稍后在渲染时通过它进行映射。 假设甚至有 20 或 50 个<path>
元素。 我基本上可以对它进行硬编码并为它们中的每一个写一个引用,但是我需要一个更好的解决方案,因为它们中的每一个都是独一无二的,并且我计划将单个节点存储在 Redux 状态中以供以后使用,因为我需要使用一些方法这需要路径长度和坐标。
我如何访问每个节点?
const pathList = [
{ d: 'M 500 500 L 800 500', fill: 'transparent', stroke: '#f00' },
{ d: 'M 810 500 L 1105 500', fill: 'transparent', stroke: '#f00' },
{ d: 'M 1110 500 L 1410 500 L 1410 810 L 810 810', fill: 'transparent', stroke: '#f00' },
{ d: 'M 800 810 L 500 810', fill: 'transparent', stroke: '#f00' },
{ d: 'M 805 495 L 805 195', fill: 'transparent', stroke: '#000' },
{ d: 'M 805 505 L 805 805', fill: 'transparent', stroke: '#000' }
];
const paths = pathList.map(path => <path d={path.d} fill={path.fill} stroke={path.stroke} />);
如果你想避免硬编码引用,你可以这样做
const paths = pathList.map((path, index) => {
this.pathRefs[index] = React.createRef();
return <path d={path.d} fill={path.fill} stroke={path.stroke} ref={this.pathRefs[index]}/>
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.