React中修改函数内width值后视图不更新如何解决?
问题原因与解决办法
问题根源
你用普通let变量存储宽度值,React不会追踪普通变量的变化。就算你修改了width的值,组件也不会重新渲染,所以视图里的div宽度不会更新。
解决方案:使用React状态(useState)
把普通变量换成React的状态变量,这样修改状态时会自动触发组件重渲染,更新视图。
修正后的TypeScript逻辑代码:
import { useState } from 'react'; // 用useState声明状态变量,初始值为'100%' const [width, setWidth] = useState<string>('100%'); const method: () => void = () => { console.log(width); // 调用setter函数修改状态 setWidth("70%"); };
修正后的视图代码:
<div style={{ width: width }} {/* 无需模板字符串,直接使用状态变量即可 */} ... 无关内容 </div>
补充说明
useState是React内置的状态管理钩子,调用setWidth时,React会标记组件需要重新渲染,更新后的状态会在下次渲染时生效。- 若要在状态更新后执行操作,可通过
useEffect监听width变化:
import { useEffect } from 'react'; useEffect(() => { console.log('更新后的width:', width); }, [width]); // 仅当width变化时执行该逻辑
内容的提问来源于stack exchange,提问作者Juan Antonio
相关产品推荐
相关产品推荐

