以下示例显示了正确和不正确的方式来操作DOM(在React的上下文中):
// -> Imports
import React,{ useEffect,useState } from "react";
// -> Element Ids
const subHeading = "sub-heading";
// -> DOM Manipulator
// -> Don't do this,opt for conditional style instead
// -> Check h1 element for example
function sideEffect() {
document.getElementById(subHeading).style.color = "red";
}
// -> Time Constant
const fiveSeconds = 5000;
export default function App() {
// -> State
const [readCond,writeCond] = useState(false);
// -> Side Effects
// -> Change readCond to true after five second pause
useEffect(() => {
setTimeout(() => writeCond(true),fiveSeconds);
},[]);
// -> Trigger DOM manipulation when readCond is true
useEffect(() => {
if (readCond) sideEffect();
},[readCond]);
return (
<div>
<h1 style={{ color: readCond ? "red" : "black" }}>React Way - Good</h1>
<h2 id={subHeading}>DOM Way - Bad</h2>
</div>
);
}
Working sandbox
本文链接:https://www.f2er.com/1367262.html