React简历生成器开发:如何将输入值渲染到新div中?
解决React中展示教育信息的问题
React是数据驱动视图的框架,别用原生JS直接操作DOM,用**状态(state)**来管理数据才是正确姿势。下面给你改好代码,实现点击保存后在表单上方展示输入的学校和专业:
修改后的完整代码(基础版)
import React, { Component } from 'react'; class Education extends Component { constructor(props) { super(props); // 初始化状态:存储输入值和是否展示已保存信息 this.state = { school: '', fieldOfStudy: '', showSavedInfo: false }; } onSubmit = (e) => { e.preventDefault(); // 从DOM获取输入值 const school = document.getElementById("school-form").value; const fieldOfStudy = document.getElementById("study-form").value; // 更新状态,触发视图重新渲染 this.setState({ school, fieldOfStudy, showSavedInfo: true }); // 清空输入框 document.getElementById("school-form").value = ''; document.getElementById("study-form").value = ''; }; render() { return ( <> <h1 className="title">Education</h1> <div id="content"> {/* 根据状态判断是否展示已保存的信息 */} {this.state.showSavedInfo && ( <div className="saved-education"> <em>School: {this.state.school}</em> <br /> <em>Field of Study: {this.state.fieldOfStudy}</em> </div> )} <form> <label htmlFor="school">School</label> <input id="school-form" className="form-row" type="text" name="school" /> <label htmlFor="study">Field of Study</label> <input id="study-form" className="form-row" type="text" name="study" /> <button onClick={this.onSubmit} className="save"> Save </button> <button className="cancel">Cancel</button> </form> </div> </> ); } } export default Education;
更推荐的写法:受控组件
上面的写法还是用到了getElementById,React更推荐用受控组件,把输入框的值和状态绑定,不用手动操作DOM,代码更规范:
import React, { Component } from 'react'; class Education extends Component { constructor(props) { super(props); this.state = { school: '', fieldOfStudy: '', showSavedInfo: false }; } // 处理输入框变化,实时更新状态 handleInputChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }); }; onSubmit = (e) => { e.preventDefault(); // 直接用状态里的值,不用操作DOM this.setState({ showSavedInfo: true }); // 如果需要清空输入框,就重置对应状态 // this.setState({ school: '', fieldOfStudy: '', showSavedInfo: true }); }; render() { return ( <> <h1 className="title">Education</h1> <div id="content"> {this.state.showSavedInfo && ( <div className="saved-education"> <em>School: {this.state.school}</em> <br /> <em>Field of Study: {this.state.fieldOfStudy}</em> </div> )} <form> <label htmlFor="school">School</label> <input id="school-form" className="form-row" type="text" name="school" value={this.state.school} onChange={this.handleInputChange} /> <label htmlFor="study">Field of Study</label> <input id="study-form" className="form-row" type="text" name="study" value={this.state.fieldOfStudy} onChange={this.handleInputChange} /> <button onClick={this.onSubmit} className="save"> Save </button> <button className="cancel">Cancel</button> </form> </div> </> ); } } export default Education;
核心思路
- 用
state存储需要展示的数据(学校、专业)和控制展示的开关(showSavedInfo) - 点击保存时,把输入的值存入
state,React会自动根据新状态重新渲染页面,展示对应的div - 受控组件写法让输入框的值和状态双向绑定,不用手动操作DOM,更符合React的设计思想
内容的提问来源于stack exchange,提问作者Dagger
相关产品推荐
相关产品推荐

