React类组件中如何使用useRef?请求技术指导
类组件中如何替代useRef实现DOM引用
useRef是React Hook,仅能在函数组件和自定义Hook中使用,类组件要获取DOM元素引用,需要使用React.createRef() API,下面是针对你的代码的改造方案:
步骤1:在类中声明Refs
在类组件内部直接声明各个输入框的引用(类字段语法,无需构造函数):
typeRef = React.createRef(); titleRef = React.createRef(); bodyRef = React.createRef();
步骤2:给输入元素绑定Ref
需要确保自定义组件(如UserPostInput)能把ref传递给内部的原生<input>元素。如果是自定义函数组件,需要用React.forwardRef包装;如果是类组件,直接通过ref属性传递即可。修改render中的输入元素:
// Type输入框 <UserPostInput type="text" place="Type of article" name="type" ref={this.typeRef} // 绑定ref /> // Title输入框 <UserPostInput type="text" place="Title of your Article" name="title" ref={this.titleRef} // 绑定ref /> // 文章内容textarea <textarea className="form-control" name="article" rows="3" ref={this.bodyRef} // 绑定ref ></textarea>
步骤3:在提交时获取Ref的值
移除原来依赖state存储输入的逻辑,在提交按钮的点击事件中直接从ref中获取当前输入值:
postHandler = (e) => { e.preventDefault(); // 从ref中提取输入值 const articleData = { id: null, type: this.typeRef.current.value, title: this.titleRef.current.value, body: this.bodyRef.current.value, author: "Suresh" }; console.log("提交数据:", articleData); // 此处添加提交逻辑(如调用后端API) };
完整修改后的代码
import React, { Component, createRef } from "react"; class PostArticle extends Component { // 声明输入框引用 typeRef = createRef(); titleRef = createRef(); bodyRef = createRef(); // 提交处理函数 postHandler = (e) => { e.preventDefault(); const articleData = { id: null, type: this.typeRef.current.value, title: this.titleRef.current.value, body: this.bodyRef.current.value, author: "Suresh", }; console.log("提交的文章数据:", articleData); // 执行提交逻辑 }; render() { return ( <UserPostContainr> <UserPostForm> <div className="mb-3 text-center fw-1"> <UserPostLabel name="Type" /> <UserPostInput type="text" place="Type of article" name="type" ref={this.typeRef} /> </div> <div className="mb-3 text-center fw-1"> <UserPostLabel name="Title" /> <UserPostInput type="text" place="Title of your Article" name="title" ref={this.titleRef} /> </div> <div className="mb-3 text-center fw-1"> <UserPostLabel name="Write your article" /> <textarea className="form-control" name="article" rows="3" ref={this.bodyRef} ></textarea> </div> <button className="btn btn-primary" onClick={this.postHandler}> Submit </button> </UserPostForm> </UserPostContainr> ); } } export default PostArticle;
关键注意事项
- 若
UserPostInput是自定义函数组件,需用forwardRef传递ref:const UserPostInput = React.forwardRef((props, ref) => { return <input ref={ref} {...props} />; }); - 类组件也可使用
this.refs旧API,但React官方推荐createRef,前者存在类型检查缺失、潜在性能问题等缺陷。 - 用ref存储输入值不会触发组件重渲染,适合仅在提交时获取值的场景;若需实时响应输入变化(如实时验证、预览),仍需结合state使用。
内容的提问来源于stack exchange,提问作者Suman kumar
相关产品推荐
相关产品推荐

