如何修复React中手动调整编辑器窗口后SIZE按钮失效问题?
解决方案
问题出在你用布尔值仅控制两种固定高度状态,用户手动调整编辑器大小后,浏览器会给textarea添加内联高度样式,但点击SIZE按钮时,CSS里的固定height会覆盖用户的手动调整。我们需要扩展状态类型,区分「默认小尺寸」「按钮触发的大尺寸」「用户自定义尺寸」三种状态,让按钮操作和手动调整互不干扰。
步骤1:修改状态类型(App.js)
把原布尔类型的editorSize改成字符串,用来区分三种状态:
import { useState } from 'react'; import Editor from './components/Editor'; function App() { const [content, setContent] = useState("") function handleChange(event) { setContent(event.target.value) } // 三种状态:default(初始小尺寸)、max(按钮最大化)、custom(用户手动调整) const [editorSize, setEditorSize] = useState("default") function toggleEditorSize() { setEditorSize(prevState => { // 点击按钮时,在默认和最大化之间切换,忽略自定义状态 return prevState === "default" ? "max" : "default"; }) } // 用户手动调整后,切换到自定义状态 function handleEditorResize() { setEditorSize("custom"); } return ( <div className="App"> <Editor handleChange={handleChange} toggleEditorSize={toggleEditorSize} editorSize={editorSize} handleEditorResize={handleEditorResize} /> </div> ); } export default App;
步骤2:监听用户调整事件(Editor.js)
给textarea添加鼠标松开和失去焦点事件,捕获用户手动调整的操作:
export default function Editor(props) { return ( <div> <div className="editor-header"> <p className="editor-title">Editor</p> <button onClick={props.toggleEditorSize}>SIZE</button> </div> <textarea id="editor" className={ props.editorSize === "max" ? "max" : props.editorSize === "default" ? "default" : "" } onChange={props.handleChange} onMouseUp={props.handleEditorResize} onBlur={props.handleEditorResize} > </textarea> </div> ) }
步骤3:调整CSS规则(Index.css)
移除固定height,改为按状态设置高度,保留min/max限制:
#editor { background-color: white; color: black; border: 2px solid black; position: relative; display: inline-block; overflow: scroll; border-top: none; min-width: 500px; min-height: 300px; max-width: 500px; max-height: 600px; } #editor.default { height: 300px; } #editor.max { height: 600px; }
原理说明
- 当用户点击SIZE按钮时,状态在
default和max之间切换,CSS会设置固定高度,覆盖可能存在的自定义内联样式。 - 当用户手动调整编辑器大小,
handleEditorResize会将状态设为custom,此时textarea没有固定高度的类,保留用户调整的内联高度,同时受min/max-height限制。
内容的提问来源于stack exchange,提问作者Anukrati Mehta
相关产品推荐
相关产品推荐

