我有一個包含多個顏色元素的 SVG/按鈕。這個想法是讓元素在 mouseEnter 上一個一個地滑入,然后在 mouseLeave 上從另一側離開,然后重置以便再次執行。使用 [...e.target.children] 創建數組時,后續的 forEach 函數正常工作。使用 getElementById 并轉換為數組時,出現錯誤“不是函數。前者返回一個實際元素的列表,而后者只返回一個列表。如何正確轉換數組以便 forEach 函數工作?<svg id="HeroButton" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 270 48"> <title>HeroButton</title> <polygon className="pink" points="29 23 52 0 15 0 0 0 0 48 15 48 54 48 29 23" fill="#ed3e88"/> <polygon className="yellow" points="97.5 40.5 114 24 96 24 96 0 52 0 29 23 54 48 82 48 82 40.5 97.5 40.5" fill="#fded52"/> <polygon className="turq" points="155.5 19.5 175 0 116 0 96 0 96 24 114 24 97.5 40.5 82 40.5 82 48 116 48 156.5 48 185 19.5 155.5 19.5" fill="#17adcb"/> <polygon className="beige" points="224.5 33 224.5 13.5 238 0 189 0 175 0 155.5 19.5 185 19.5 156.5 48 189 48 239.5 48 224.5 33" fill="#ffffc7"/> <polygon className="turq2" points="243 0 238 0 224.5 13.5 224.5 33 239.5 48 243 48 270 48 270 0 243 0" fill="#17adcb"/></svg>export default class HeroButton extends React.Component { constructor(props) { super(props); this.state = { translate: "translateX(100%)", opacity: 1 } }; componentDidMount() { // const polygons = [...document.getElementById('HeroButton').children; const polygons = Array.from(document.getElementById('HeroButton').children); console.log({polygons}) this.updatePolygons(polygons); this.setState({ translate: "translateX(-100%)", opacity: 0 }); }; handleMouseEnter = (polygons) => { this.updatePolygons(polygons) }; handleMouseLeave = (polygons) => { this.setState({ translate: "translateX(100%)", opacity: 1 }); }; updatePolygons = (polygons) => { // const polygons = [...e.target.children]; polygons.forEach(child => { child.style.transform = this.state.translate; child.style.opacity = this.state.opacity; });
為什么 forEach 與 e.target.children 一起工作
Cats萌萌
2021-08-20 19:14:30