gpt4 book ai didi

javascript - 访问相似的 DOM 元素

转载 作者:行者123 更新时间:2023-12-02 22:24:46 26 4
gpt4 key购买 nike

我目前正在开发一个组件,我需要访问每个 <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]}/>
});

关于javascript - 访问相似的 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59105626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com