React表单组件转TypeScript报_title属性不存在如何解决
报错原因
报错Property '_title' does not exist on type 'FormComp'是因为TypeScript的静态类型检查要求类的所有实例属性必须提前做类型声明,原JavaScript代码里通过ref回调给组件实例动态挂载_title属性的写法,在TS环境下没有提前声明属性和对应类型,就会触发检查报错。
符合TypeScript规范的改写方案
核心需要做3处调整:
- 提前在类中声明
_title实例属性的类型,该属性绑定原生input DOM节点,类型为HTMLInputElement | null(ref回调在组件卸载时会传入null,所以类型需要包含null) - 明确组件Props、State的类型定义,避免隐式
any - 读取ref值时增加非空判断,避免运行时出现空指针错误
改写后的完整代码如下:
import React from 'react'; // 定义Props类型,当前无外部传入props可声明为空类型 type FormCompProps = {} // 定义State类型,当前state无字段可声明为空类型 type FormCompState = {} class FormComp extends React.Component<FormCompProps, FormCompState> { // 提前声明ref挂载的实例属性及类型 private _title: HTMLInputElement | null = null; constructor(props: FormCompProps) { super(props); this.state = {}; // 可在构造函数统一绑定方法this指向,替代render里重复写bind this.handleCreate = this.handleCreate.bind(this); } handleCreate(event: React.FormEvent<HTMLButtonElement>) { event.preventDefault(); // 增加ref非空判断,避免空指针报错 if (!this._title) return; const title = this._title.value; const temp = { title: title }; // 原有ajax发送等业务逻辑保留即可 } render() { return ( <div className="col-md-12"> <input type="text" className="col-sm-3 form-control" placeholder="Title" ref={(c) => (this._title = c)} /> <button type="button" className="btn btn-primary" onClick={this.handleCreate} > Create </button> </div> ); } } export default FormComp;
补充:如果使用React 16.3+版本,更推荐用
React.createRef写法,ref类型可自动推导,代码更简洁:class FormComp extends React.Component<FormCompProps, FormCompState> { private _titleRef = React.createRef<HTMLInputElement>(); handleCreate(event: React.FormEvent<HTMLButtonElement>) { event.preventDefault(); // 可选链+空值合并做安全取值 const title = this._titleRef.current?.value ?? ''; const temp = { title }; // 后续业务逻辑保持不变 } render() { return ( <div className="col-md-12"> <input type="text" className="col-sm-3 form-control" placeholder="Title" ref={this._titleRef} /> {/* 其余按钮等DOM结构和之前一致 */} </div> ) } }
内容的提问来源于stack exchange,提问作者Tjax
相关产品推荐
相关产品推荐

