React问题:点击按钮后h1颜色未改变,修改innerText却正常?
问题分析与解决方案
核心问题
- DOM样式修改方式错误
直接给DOM元素赋值color属性不会生效,DOM元素的CSS样式必须通过style对象来操作,正确写法是hRef.current.style.color。 - 多余的状态更新触发
useEffect里的setState1(state1)完全没必要,这会导致额外的组件渲染,甚至在Strict模式下引发重复执行的问题。
修正后的代码
export function App(props) { const [state1, setState1] = useState(true); const hRef = useRef(); const clickHandler = () => { setState1(!state1); }; useEffect(() => { // 通过style对象修改颜色 hRef.current.style.color = state1 ? 'blue' : 'green'; // 移除不必要的setState调用 }, [state1]); return ( <div className='App'> <h1 ref={hRef}>Hello {`${state1}`}.</h1> <button onClick={clickHandler}>Change State</button> </div> ); }
更符合React范式的写法
其实完全不需要使用useRef和useEffect直接操作DOM,React推荐通过状态直接驱动样式,代码更简洁易维护:
export function App(props) { const [state1, setState1] = useState(true); const clickHandler = () => { setState1(!state1); }; return ( <div className='App'> <h1 style={{ color: state1 ? 'blue' : 'green' }}>Hello {`${state1}`}.</h1> <button onClick={clickHandler}>Change State</button> </div> ); }
内容的提问来源于stack exchange,提问作者Wojtek Urbański
相关产品推荐
相关产品推荐

