You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React.Component中实现添加工作经历表单的显示与隐藏?

在React类组件中实现工作经历表单的显示/隐藏控制

在React中,我们通过**组件状态(state)**来管理UI的显示/隐藏,而非直接操作DOM样式。以下是针对你的代码的完整修改方案:

步骤1:初始化组件状态

在WorkExperience类中添加状态,用来控制表单可见性和存储工作经历数据:

constructor(props) {
  super(props);
  this.state = {
    isFormVisible: false, // 初始状态隐藏表单
    workExperience: [
      {
        title: "title",
        company: "company",
        location: "location",
        description: "description",
      },
    ]
  };
}

步骤2:实现显示/隐藏及表单处理方法

添加三个核心方法:切换表单显示状态、处理表单提交、处理取消操作:

// 切换表单显示/隐藏状态
toggleForm = () => {
  this.setState(prevState => ({
    isFormVisible: !prevState.isFormVisible
  }));
};

// 处理表单提交逻辑
handleFormSubmit = (e) => {
  e.preventDefault(); // 阻止默认表单跳转行为
  
  // 获取表单输入值
  const title = e.target.title.value;
  const company = e.target.company.value;
  const location = e.target.location.value;
  const description = e.target.description.value;
  
  // 更新工作经历列表并隐藏表单
  this.setState(prevState => ({
    workExperience: [...prevState.workExperience, { title, company, location, description }],
    isFormVisible: false
  }));
  
  // 重置表单内容
  e.target.reset();
};

// 处理取消按钮点击
handleCancel = () => {
  this.setState({ isFormVisible: false });
};

步骤3:条件渲染表单与工作经历列表

在render方法中,根据状态值控制表单是否渲染,同时遍历展示所有工作经历:

render() {
  const { workExperience, isFormVisible } = this.state;
  
  return (
    <>
      <div id="content" className="content">
        <h1 className="title">Work Experience</h1>
        {/* 遍历展示所有工作经历 */}
        {workExperience.map((exp, index) => (
          <div key={index} className="work-experience">
            <p>Job Title: {exp.title}</p>
            <p>Company: {exp.company}</p>
            <p>Location: {exp.location}</p>
            <p>Description: {exp.description}</p>
          </div>
        ))}
      </div>
      
      <button className="form-btn" onClick={this.toggleForm}>
        + Add Work Experience
      </button>
      
      {/* 根据状态条件渲染表单 */}
      {isFormVisible && (
        <form onSubmit={this.handleFormSubmit}>
          <label htmlFor="title">Job Title</label>
          <input id="title" className="form-row" type="text" name="title" required />
          
          <label htmlFor="company">Company</label>
          <input id="company" className="form-row" type="text" name="company" required />
          
          <label htmlFor="location">Location</label>
          <input id="location" className="form-row" type="text" name="location" required />
          
          <label htmlFor="description">Job Description</label>
          <textarea rows="4" cols="50" name="description" required></textarea>
          
          <button className="save" type="submit">Save</button>
          <button className="cancel" type="button" onClick={this.handleCancel}>Cancel</button>
        </form>
      )}
    </>
  );
}

注意点:

  • React中需将HTML的for属性改为htmlFor,避免与JS关键字冲突
  • 给取消按钮设置type="button",防止触发表单默认提交行为
  • 使用map遍历工作经历列表,支持多条数据展示

可选:通过CSS类控制显示/隐藏

如果你更习惯用样式类控制,可将条件渲染改为:

<form 
  className={`experience-form ${isFormVisible ? 'visible' : 'hidden'}`}
  onSubmit={this.handleFormSubmit}
>
  {/* 表单内容 */}
</form>

然后添加CSS样式:

.experience-form.hidden {
  display: none;
}
.experience-form.visible {
  display: block;
}

完整组件代码

import React, { Component } from "react";

class WorkExperience extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isFormVisible: false,
      workExperience: [
        {
          title: "title",
          company: "company",
          location: "location",
          description: "description",
        },
      ]
    };
  }

  toggleForm = () => {
    this.setState(prevState => ({
      isFormVisible: !prevState.isFormVisible
    }));
  };

  handleFormSubmit = (e) => {
    e.preventDefault();
    const title = e.target.title.value;
    const company = e.target.company.value;
    const location = e.target.location.value;
    const description = e.target.description.value;

    this.setState(prevState => ({
      workExperience: [...prevState.workExperience, { title, company, location, description }],
      isFormVisible: false
    }));

    e.target.reset();
  };

  handleCancel = () => {
    this.setState({ isFormVisible: false });
  };

  render() {
    const { workExperience, isFormVisible } = this.state;
    return (
      <>
        <div id="content" className="content">
          <h1 className="title">Work Experience</h1>
          {workExperience.map((exp, index) => (
            <div key={index} className="work-experience">
              <p>Job Title: {exp.title}</p>
              <p>Company: {exp.company}</p>
              <p>Location: {exp.location}</p>
              <p>Description: {exp.description}</p>
            </div>
          ))}
        </div>

        <button className="form-btn" onClick={this.toggleForm}>
          + Add Work Experience
        </button>

        {isFormVisible && (
          <form onSubmit={this.handleFormSubmit}>
            <label htmlFor="title">Job Title</label>
            <input id="title" className="form-row" type="text" name="title" required />

            <label htmlFor="company">Company</label>
            <input id="company" className="form-row" type="text" name="company" required />

            <label htmlFor="location">Location</label>
            <input id="location" className="form-row" type="text" name="location" required />

            <label htmlFor="description">Job Description</label>
            <textarea rows="4" cols="50" name="description" required></textarea>

            <button className="save" type="submit">Save</button>
            <button className="cancel" type="button" onClick={this.handleCancel}>Cancel</button>
          </form>
        )}
      </>
    );
  }
}

export default WorkExperience;

内容的提问来源于stack exchange,提问作者Dagger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:50:21