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

React.js中如何将Header组件的selectedMonth传入App的Api.create方法?

React子组件向父组件传值实现方案

要实现子组件Header的选中月份传递给父组件App的API调用,核心方案是状态提升——把selectedMonth这个需要共享的状态放到父组件App中,子组件通过props接收状态和回调函数,触发下拉框变化时通知父组件更新状态,这样App就能拿到这个值去过滤API数据了。

第一步:改造App.js

  1. 在App的state中新增selectedMonth,初始值与Header原逻辑一致,使用formatMonth(defaultMonth)(注意确保defaultMonth和formatMonth在App中可访问,比如从工具文件导入)
  2. 新增回调函数handleMonthChange,接收Header传来的选中月份并更新App状态
  3. 修改getWOT方法,将selectedMonth作为参数传给API接口
  4. 渲染Header时,把selectedMonth和handleMonthChange通过props传递给子组件

修改后的App.js代码:

import React, { Component } from 'react';
import Header from './Header';
// 根据实际情况导入工具函数
import { formatMonth, defaultMonth } from './utils';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: false,
      allWOT: [],
      selectedMonth: formatMonth(defaultMonth) // 新增选中月份状态
    };

    this.handleMonthChange = this.handleMonthChange.bind(this);
    this.getWOT = this.getWOT.bind(this);
  }

  // 接收子组件传来的选中月份并更新状态
  handleMonthChange(selectedMonth) {
    this.setState({ selectedMonth }, () => {
      // 状态更新后自动调用API获取过滤后的数据
      this.getWOT();
    });
  }

  getWOT() {
    this.setState({ isLoading: true });
    // 将selectedMonth作为参数传入API接口
    Api.create().getWOT(this.state.selectedMonth).then(res => {
      if (res.ok) {
        if (res.data) {
          this.setState({ 
            allWOT: res.data.Result, 
            isLoading: false 
          });
        } else {
          window.alert(res.problem);
          this.setState({ isLoading: false });
        }
      } else {
        window.alert('请求失败');
        this.setState({ isLoading: false });
      }
    }).catch(err => {
      window.alert(`请求出错:${err.message}`);
      this.setState({ isLoading: false });
    });
  }

  // 组件挂载时初始化数据
  componentDidMount() {
    this.getWOT();
  }

  render() {
    const renderusers = _.map(this.state.allWOT, (value) => (
      <div className="line-bars" key={value.id}> {/* 添加key避免React警告 */}
        <div className="bar-title">Total Reject</div>
        <div className="container">
          {/* 渲染具体数据 */}
        </div>
      </div>
    ));

    return (
      this.state.isLoading ?
        <h3 style={{ textAlign: 'center' }}>loading...</h3>
        :
        <div>
          {/* 传递状态和回调给Header */}
          <Header 
            selectedMonth={this.state.selectedMonth} 
            onMonthChange={this.handleMonthChange} 
          />
          <div className="grid-container">
            <div className="main-grid">
              {/* 主内容区域 */}
            </div>
            {renderusers}
          </div>
        </div>
    );
  }
}
export default App;

第二步:改造Header.js

  1. 移除组件内部的selectedMonth状态,改为通过props接收父组件传来的值
  2. 修改onChange方法,触发时调用父组件传来的onMonthChange回调,传递格式化后的月份
  3. 调整Dropdown的value绑定(如果需要保留原始选中值,可保留内部的value状态)

修改后的Header.js代码:

import React, { Component } from 'react';
import { formatMonth } from './utils';

class Header extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '' // 保留Dropdown的原始选中值(可选,根据组件需求调整)
    };

    this.onChange = this.onChange.bind(this);
  }

  onChange(event) {
    const formattedMonth = formatMonth(event.value);
    // 调用父组件的回调函数,传递格式化后的月份
    this.props.onMonthChange(formattedMonth);
    // 更新Dropdown的原始选中值
    this.setState({ value: event.value });
  }

  render() {
    return (
      <header className="header">
        <Dropdown 
          className="dropdown-month" 
          value={this.state.value} 
          onChange={this.onChange} 
        />
      </header>
    );
  }
}

export default Header;

关键说明

  • 状态提升:将父子共享的状态放在父组件,子组件仅负责UI交互,通过回调通知父组件更新状态
  • props传递:父组件通过props向子组件传递状态和回调函数,子组件依赖props完成交互逻辑
  • API触发时机:示例中在状态更新后自动调用API,也可根据需求添加按钮手动触发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 22:54:18