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

React入门:如何为多个Counter组件按钮设置自定义名称?

实现方法

要让每个按钮显示不同的标识文本,核心是通过**组件属性(props)**给每个Counter实例传递自定义内容,具体修改如下:

1. 修改App.js(父组件)

给每个Counter组件传入label属性,指定对应的标识字母:

import React,{useState} from 'react';
import Counter from './components/Counter'

function App() {
  return (
    <div className="App">
      <h1>Code</h1>
      <Counter label="a" />
      <Counter label="b" />
      <Counter label="c" />
    </div>
  );
}
export default App;

2. 修改Counter.js(子组件)

接收父组件传递的label属性,并在按钮文本中使用:

import React, {useState} from 'react'

// 通过解构赋值直接获取label属性
const Counter = ({ label }) => {
    const [count, setCount] = useState(0)
  
  const increment = () => {
    setCount(count + 1)
  }
  return (
      <button onClick={increment}>
        Click {label} {count}
      </button>
  );
}

export default Counter;

原理说明

props是React中组件间传递数据的基础方式,父组件可以给子组件传递任意类型的数据,子组件接收后就能在内部渲染或逻辑中使用。这样每个Counter实例会根据收到的label值,显示对应的"click a {count}"、"click b {count}"等文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:54:32