我正在研究我的第一个React应用程序,试图了解我是如何在页面中使用小型JS代码段的。
例如;我想在我的代码中使用以下Interactive SVG Chris Coyer。添加HTML和CSS很容易,但实现JS的正确方法是什么?
复制并粘贴到我的home.js页面显然不起作用。
var wordStates = document.querySelectorAll(".list-of-states li");
var svgStates = document.querySelectorAll("#states > *");
function removeAllOn() {
wordStates.forEach(function(el) {
el.classList.remove("on");
});
svgStates.forEach(function(el) {
el.classList.remove("on");
});
}
function addOnFromList(el) {
var stateCode = el.getAttribute("data-state");
var svgState = document.querySelector("#" + stateCode);
el.classList.add("on");
svgState.classList.add("on");
}
function addOnFromState(el) {
var stateId = el.getAttribute("id");
var wordState = document.querySelector("[data-state='" + stateId + "']");
el.classList.add("on");
wordState.classList.add("on");
}
wordStates.forEach(function(el) {
el.addEventListener("mouseenter", function() {
addOnFromList(el);
});
el.addEventListener("mouseleave", function() {
removeAllOn();
});
el.addEventListener("touchstart", function() {
removeAllOn();
addOnFromList(el);
});
});
svgStates.forEach(function(el) {
el.addEventListener("mouseenter", function() {
addOnFromState(el);
});
el.addEventListener("mouseleave", function() {
removeAllOn();
});
el.addEventListener("touchstart", function() {
removeAllOn();
addOnFromState(el);
});
});
答案 0 :(得分:1)
您可以通过将wordStates
和svgStates
添加为类变量并通过将查询选择器函数添加到componentdid挂载函数中来操作组件中来使用它,例如,
import * as React from 'react';
import { Component } from "react";
class Home extends Component {
constructor(props) {
super(props);
this.wordStates=[];
this.svgStates=[];
}
removeAllOn =()=> {
this.wordStates.forEach(function (el) {
el.classList.remove("on");
});
this.svgStates.forEach(function (el) {
el.classList.remove("on");
});
}
addOnFromList=(el)=> {
var stateCode = el.getAttribute("data-state");
var svgState = document.querySelector("#" + stateCode);
el.classList.add("on");
svgState.classList.add("on");
}
addOnFromState=(el)=> {
var stateId = el.getAttribute("id");
var wordState = document.querySelector("[data-state='" + stateId + "']");
el.classList.add("on");
wordState.classList.add("on");
}
componentDidMount() {
this.wordStates = document.querySelectorAll(".list-of-states li");
this.svgStates = document.querySelectorAll("#states > *");
this.wordStates.forEach(function (el) {
el.addEventListener("mouseenter", function () {
addOnFromList(el);
});
el.addEventListener("mouseleave", function () {
removeAllOn();
});
el.addEventListener("touchstart", function () {
removeAllOn();
addOnFromList(el);
});
});
this.svgStates.forEach(function (el) {
el.addEventListener("mouseenter", function () {
addOnFromState(el);
});
el.addEventListener("mouseleave", function () {
removeAllOn();
});
el.addEventListener("touchstart", function () {
removeAllOn();
addOnFromState(el);
});
});
}
}