如何实现点击React自定义textarea组件时自动完全展开?
React textarea 点击自动完全展开实现方案
以下是修改后可直接使用的组件代码:
class DynamicWidthInput extends React.Component { constructor(props) { super(props); this.state = { isExpanded: false }; this.textareaRef = React.createRef(); } componentDidMount() { const { id, value } = this.props; resizable(document.getElementById(id), 16, value); } componentDidUpdate(prevProps) { const { id, value } = this.props; // 展开状态下不执行原有resizable逻辑,避免覆盖展开高度 if (this.props.value !== prevProps.value && !this.state.isExpanded) { resizable(document.getElementById(id), 16, value); } } handleTextareaFocus = () => { this.setState({ isExpanded: true }, () => { const textareaEl = this.textareaRef.current; if (textareaEl) { // 直接设置高度为内容滚动高度,实现完全展开 textareaEl.style.height = `${textareaEl.scrollHeight}px`; } }); } render() { const { id, placeholder, type, onChange, value, error, size } = this.props; if (type === "textarea") { return ( <div style={{ display: "inline-block", verticalAlign: "top" }}> <textarea className={`input dynamic-input dynamic-textarea ${size}`} id={id} onChange={onChange} placeholder={placeholder} value={value} wrap="soft" maxLength="1000" ref={this.textareaRef} onFocus={this.handleTextareaFocus} {...this.props} /> {error && <p className="help is-danger">{error.message}</p>} </div> ); } // 其他类型输入框原有逻辑保持不变 ... } } export default DynamicWidthInput;
修改说明
- 新增
isExpanded状态标记textarea是否已展开,避免展开后原有resizable逻辑覆盖高度设置 - 新增textarea的ref引用,方便直接操作DOM元素设置高度
- 绑定
onFocus事件,用户点击textarea进入聚焦状态时触发展开逻辑 - 展开时直接将textarea高度设置为内容的
scrollHeight,实现完全适配内容长度的展开效果 - 原有调用代码无需修改,保持现有参数即可生效
效果对比
当前默认状态效果:
点击展开后效果:
内容的提问来源于stack exchange,提问作者Nhan Nguyen
相关产品推荐
相关产品推荐

