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

React组件Props作用域与使用问题咨询:如何在子组件中接收父组件传递的Props

解决React类组件的Props获取问题

嘿,我来帮你搞定这个Props作用域的问题!你的思路是对的,但在类组件的Props使用方式上有几个小细节没处理好,我一步步给你梳理:

问题分析

  1. 类组件的Props访问方式错误:类组件的render方法不需要接收props参数,组件传入的Props是挂载在组件实例的this.props上的,你现在写的render(props)相当于定义了一个局部变量,根本拿不到外部传入的属性。
  2. 组件名拼写不一致:你的文件名是PrimaryButton.js,但组件类名和调用时用的是PrimaryBouton,虽然语法上没问题,但容易混淆,建议统一命名。
  3. Props命名不规范:React社区约定Props用小驼峰命名(比如type而非Type),这样更符合JSX的编码习惯。
  4. 缺少组件导入:你的App.js里没有导入PrimaryButton组件,运行时会直接报错。

修改后的完整代码

App.js

// 记得导入组件
import PrimaryButton from './PrimaryButton';

function App() {
  return (
    <div className="App">
      {/* 用小驼峰命名Props,组件名统一为PrimaryButton */}
      <PrimaryButton type='primary' title='Lorem Ipsum'/>
    </div>
  );
}
export default App;

PrimaryButton.js

import './PrimaryButton.css';
import React from 'react';

// 统一组件类名为PrimaryButton
class PrimaryButton extends React.Component {
  // render方法不需要接收props参数
  render() {
    // 通过this.props访问传入的属性
    return (
      <button className={this.props.type}>
        <span>{this.props.title}</span>
      </button>
    );
  }
}
export default PrimaryButton;

额外小提示

如果你觉得每次写this.props有点麻烦,也可以在render方法里解构Props,让代码更简洁:

class PrimaryButton extends React.Component {
  render() {
    // 解构Props,直接使用变量
    const { type, title } = this.props;
    return (
      <button className={type}>
        <span>{title}</span>
      </button>
    );
  }
}

这样修改后,你就能通过App.js传入的Props正确设置按钮的CSS类和文本啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:47:30