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

React组件间传递onClick值:Tournaments向Template传赛事ID

嘿,我来帮你理顺这个组件传值的问题~

首先得纠正一个小误区:你提到尝试用子向父传props,但其实你的需求是父组件(Tournaments)把选中的赛事ID传给子组件(Template),这是标准的父到子传值场景,用普通的props传递就能搞定,不用复杂的子向父回调逻辑。

下面是具体的实现步骤和代码示例:

步骤1:在Tournaments组件中管理选中的赛事ID状态

我们需要在父组件里维护一个状态,用来存储用户点击的赛事ID,然后把这个状态作为props传给Template。

修改后的Tournaments.js代码:

import React, { Component } from "react";
import Template from './Template';

class Tournaments extends Component {
  constructor(props) {
    super(props);
    // 初始化状态:赛事列表 + 选中的赛事ID
    this.state = {
      tournaments: [],
      selectedTournamentId: null
    };
  }

  // 组件挂载时获取赛事列表API数据
  componentDidMount() {
    // 替换成你的赛事列表API地址
    fetch('https://your-api-url/tournaments')
      .then(res => res.json())
      .then(data => this.setState({ tournaments: data }))
      .catch(err => console.error('获取赛事列表失败:', err));
  }

  // 点击赛事名称时更新选中ID的状态
  handleTournamentClick = (tournamentId) => {
    this.setState({ selectedTournamentId: tournamentId });
  }

  render() {
    const { tournaments, selectedTournamentId } = this.state;
    return (
      <div className="tournaments-container">
        <h2>赛事列表</h2>
        <ul>
          {tournaments.map(tournament => (
            <li 
              key={tournament.id}
              onClick={() => this.handleTournamentClick(tournament.id)}
              style={{ cursor: 'pointer', color: selectedTournamentId === tournament.id ? '#2563eb' : 'inherit' }}
            >
              {tournament.name}
            </li>
          ))}
        </ul>
        {/* 把选中的赛事ID作为props传给Template组件 */}
        <Template tournamentId={selectedTournamentId} />
      </div>
    );
  }
}

export default Tournaments;

步骤2:在Template组件中接收ID并请求对应数据

Template组件接收父组件传来的tournamentId props,当ID变化时,自动触发API请求获取对应赛事的详情数据。

修改后的Template.js代码:

import React, { Component } from "react";

class Template extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tournamentData: null,
      loading: false,
      error: null
    };
  }

  // 监听props变化:当tournamentId改变时重新请求数据
  componentDidUpdate(prevProps) {
    if (this.props.tournamentId !== prevProps.tournamentId && this.props.tournamentId) {
      this.fetchTournamentDetails(this.props.tournamentId);
    }
  }

  // 请求单赛事详情的API函数
  fetchTournamentDetails = (tournamentId) => {
    this.setState({ loading: true, error: null });
    // 替换成你的单赛事详情API地址
    fetch(`https://your-api-url/tournaments/${tournamentId}`)
      .then(res => res.json())
      .then(data => this.setState({ tournamentData: data, loading: false }))
      .catch(err => {
        this.setState({ error: '获取赛事详情失败', loading: false });
        console.error(err);
      });
  }

  render() {
    const { tournamentData, loading, error } = this.state;
    const { tournamentId } = this.props;

    if (!tournamentId) {
      return <p>请选择一个赛事查看详情</p>;
    }

    if (loading) {
      return <p>加载中...</p>;
    }

    if (error) {
      return <p className="text-red-500">{error}</p>;
    }

    return tournamentData ? (
      <div className="tournament-details">
        <h3>{tournamentData.name} 赛事详情</h3>
        <p>赛事ID:{tournamentData.id}</p>
        <p>举办时间:{tournamentData.date}</p>
        <p>举办地点:{tournamentData.location}</p>
        {/* 这里可以根据你的API数据渲染更多内容 */}
      </div>
    ) : null;
  }
}

export default Template;

关键逻辑说明

  • 状态管理:在Tournaments中用selectedTournamentId状态记录用户选中的赛事ID,点击事件触发状态更新,这是React管理用户交互状态的标准方式。
  • 父到子传值:通过Template tournamentId={selectedTournamentId}把ID传给子组件,这是React中最基础的组件通信方式。
  • 监听props变化:Template中用componentDidUpdate监听tournamentId的变化,只要ID改变就自动请求新数据,实现了选中赛事后详情自动更新的效果。
  • 用户体验优化:加入了加载状态、错误提示和未选择时的引导文案,让页面交互更友好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:22:10