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

React中点击按钮如何渲染Navbar与Matchinfo多个组件

实现点击"View Stats"按钮渲染Navbar和Matchinfo组件的方案

Hey there! Let's get that "View Stats" button working to show your Navbar and Matchinfo components properly. Here's a straightforward, step-by-step solution tailored to your existing class components:


Step 1: Update the Content Component State & Add Click Handler

First, we need to track two key things in the Content component's state: whether to show the match details view, and which specific match was selected. We'll also add a handler function to trigger the view switch when the button is clicked.

Modify your Content.js like this:

import React, { Component } from 'react';
import './content.css';
import Navbar from './Navbar'; // Import the Navbar component
import Matchinfo from './Matchinfo'; // Import the Matchinfo component

class Content extends Component {
 constructor(props){
 super(props);
 this.state = { 
   matches:[], 
   loading:true,
   showMatchDetails: false, // 新增:控制是否显示详情页
   selectedMatchId: null // 新增:记录选中的比赛ID
 };
 // 绑定事件处理函数,确保this指向正确
 this.handleViewStats = this.handleViewStats.bind(this);
 }

 // 新增:处理按钮点击,切换到详情页
 handleViewStats(matchId) {
   this.setState({
     showMatchDetails: true,
     selectedMatchId: matchId
   });
 }

 componentDidMount(){
 fetch('api/matches')
 .then(res => res.json())
 .then(res => {
 console.log(res)
 this.setState({ matches:res.slice(0,16), loading:false })
 })
 }

 renderMatches() {
 return this.state.matches.map(match => {
 return (
 <div className="col-lg-3"> {/* 注意:React中用className替代class */}
 <div id="content">
 <p className="match">MATCH {match.id}</p>
 <h4>{match.team1}</h4>
 <p>VS</p>
 <h4>{match.team2}</h4>
 <div className="winner">
 <h3>WINNER</h3>
 <h4>{match.winner}</h4>
 </div>
 <div className="stats">
 {/* 更新按钮,绑定点击事件并传递当前比赛ID */}
 <button 
   type="button" 
   className="btn btn-success"
   onClick={() => this.handleViewStats(match.id)}
 >
   View Stats
 </button>
 </div>
 </div>
 </div>
 );
 })
 }

 render() {
 if (this.state.loading) {
 return <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" alt="Loading" />
 }

 // 如果需要显示详情页,渲染Navbar和Matchinfo组件
 if (this.state.showMatchDetails) {
   return (
     <div>
       <Navbar />
       <Matchinfo matchId={this.state.selectedMatchId} />
     </div>
   );
 }

 // 否则渲染比赛列表
 return (
 <div>
 <div className="row"> {/* 用className替代class */}
 {this.renderMatches()}
 </div>
 </div>
 );
 }
}
export default Content;

Step 2: Fix the Matchinfo Component's API Request

Your current Matchinfo component uses a hardcoded URL (api/match/:match_id). We need to use the matchId passed via props to fetch data for the selected match. We'll also add error handling and support for prop updates:

Modify your Matchinfo.js like this:

import React, { Component } from 'react';

class Matchinfo extends Component {
 constructor(props){
 super(props);
 this.state = { info:[], loading:true };
 }

 componentDidMount(){
 this.fetchMatchData();
 }

 // 新增:封装数据请求逻辑,使用props中的matchId
 fetchMatchData() {
   const { matchId } = this.props;
   fetch(`api/match/${matchId}`) // 用模板字符串注入选中的比赛ID
   .then(res => res.json())
   .then(res => {
     console.log(res)
     this.setState({ info:res, loading:false })
   })
   .catch(err => console.error('获取比赛详情失败:', err)); // 新增错误捕获
 }

 // 可选:当props中的matchId变化时,重新请求数据
 componentDidUpdate(prevProps) {
   if (prevProps.matchId !== this.props.matchId) {
     this.setState({ loading: true });
     this.fetchMatchData();
   }
 }

 render() {
 if (this.state.loading) {
 return <img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" alt="Loading" />
 }
 const {info} = this.state;
 return (
 <div>
 <p className="match">MATCH {info.id}</p>
 <h4>{info.team1}</h4>
 <p>VS</p>
 <h4>{info.team2}</h4>
 <div className="winner">
 <h3>WINNER</h3>
 <h4>{info.winner}</h4>
 </div>
 </div>
 );
 }
}
export default Matchinfo;

Step 3: Add "Back to Home" Function (Optional)

If you want the Navbar's "Home" link to return to the match list, update the Navbar to accept a callback prop:

Update Navbar.js:

import React, { Component } from 'react';

class Navbar extends Component {
 render() {
 return (
 <div>
 <nav className="navbar navbar-inverse"> {/* 用className替代class */}
 <div className="container-fluid">
 <div className="navbar-header">
 <a className="navbar-brand" href="#">Cricket App</a>
 </div>
 <ul className="nav navbar-nav">
 {/* 点击Home时触发父组件传递的回调 */}
 <li><a href="#" onClick={this.props.onHomeClick}>Home</a></li>
 </ul>
 </div>
 </nav>
 </div>
 );
 }
}
export default Navbar;

Update Content.js's Navbar render:

<Navbar onHomeClick={() => this.setState({ showMatchDetails: false })} />

That's it! Now clicking "View Stats" on any match will switch the page to show the Navbar and detailed Matchinfo for that match. If you added the back button, clicking "Home" will take you back to the match list.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:32:21