React中如何在handleChange选中文档后在禁用输入框显示对应编码
解决方案
要实现选中文档后在禁用输入框显示对应ctd_article_code,需要通过状态管理选中的文章编码,修改事件处理逻辑获取目标值,最后将禁用输入框与状态绑定,具体步骤如下:
1. 更新状态结构
在state中新增字段存储选中的文章编码:
state = { articles:[ {id:0, ctd_article_code:"ART001", ctd_article_libelle: "文章示例1", ctd_titre:{ id: '', ctd_titre_code: "", ctd_titre_libelle: "" }, ctd_chapitre:{ id: '', ctd_chapitre_libelle: "", ctd_chapitre_code: "", ctd_titre: { id: 1, ctd_titre_code: "", ctd_titre_libelle: "" } } }, {id:1, ctd_article_code:"ART002", ctd_article_libelle: "文章示例2", ctd_titre:{ id: '', ctd_titre_code: "", ctd_titre_libelle: "" }, ctd_chapitre:{ id: '', ctd_chapitre_libelle: "", ctd_chapitre_code: "", ctd_titre: { id: 1, ctd_titre_code: "", ctd_titre_libelle: "" } } } ], ctd_paragraphe_code: '', ctd_paragraphe_libelle: '', selectedArticleCode: '' // 新增:存储选中的文章编码 }
2. 修改事件处理函数
根据选中的文章ID,从数组中匹配对应文章并提取编码更新状态:
handleChangearticles = (event) => { const selectedId = event.target.value; // 根据ID查找选中的文章 const selectedArticle = this.state.articles.find(article => article.id == selectedId); this.setState({ paragraphe_article: selectedId, // 找到文章则取编码,无匹配时设为空 selectedArticleCode: selectedArticle ? selectedArticle.ctd_article_code : '' }); }
3. 绑定禁用输入框的值
将禁用输入框的value属性与状态字段绑定(禁用控件需用value而非defaultValue,后者仅设置初始值无法随状态更新):
<div className="form-group row"> <label htmlFor="exampleInputUsername2" className="col-sm-3 col-form-label">Code </label> <div className="col-sm-3"> <input type="number" disabled className="form-control" id="exampleInputUsername2" value={this.state.selectedArticleCode} /> </div> <div className="col-sm-6"> <input type="number" min="100" max="999" onChange={this.handleCompte_code} className="form-control" id="exampleInputUsername2" placeholder="" required /> </div> </div>
补充说明
- React中统一使用
className替代class属性,避免与JavaScript关键字冲突,已同步修改代码中的相关属性。 - 若需存储完整选中文章对象,可将state字段改为
selectedArticle: null,事件处理中直接存储匹配到的文章,后续取值时用this.state.selectedArticle?.ctd_article_code(可选链操作符避免空值报错)。
内容的提问来源于stack exchange,提问作者Divac
相关产品推荐
相关产品推荐

