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

如何向React处理组件传递Props?

How to Pass Props to React Components (Using React.createClass Syntax)

Hey there! Let's break down how to pass props to your Dashboard and Comments components using the code snippet you shared. Since you're using the older React.createClass syntax, I'll tailor the examples to match that style perfectly.

Step 1: Pass Props from the Parent Component (Index)

In your Index component's render method, you can pass props to child components just like adding HTML attributes. Let's say you want to pass a user object to Dashboard and a comment count to Comments—here's how to implement that:

var Dashboard = require('./Dashboard');
var Comments = require('./Comments');

var Index = React.createClass({
  // Add sample data to pass as props (you can use your own data here)
  getInitialState: function() {
    return {
      currentUser: { name: "Alex", role: "Admin" },
      totalComments: 42
    };
  },

  render: function() {
    return (
      <div className="index-container">
        {/* Pass the user prop to Dashboard */}
        <Dashboard user={this.state.currentUser} />
        {/* Pass the comment count prop to Comments */}
        <Comments commentCount={this.state.totalComments} />
      </div>
    );
  }
});

Step 2: Receive and Use Props in Child Components

Now, in your Dashboard and Comments components, you can access these passed props using this.props:

Example Dashboard.js:

var Dashboard = React.createClass({
  render: function() {
    // Access the user prop passed from Index
    return (
      <div className="dashboard">
        <h2>Welcome back, {this.props.user.name}!</h2>
        <p>Your current role: {this.props.user.role}</p>
      </div>
    );
  }
});

module.exports = Dashboard;

Example Comments.js:

var Comments = React.createClass({
  render: function() {
    // Access the commentCount prop passed from Index
    return (
      <div className="comments-section">
        <h3>Recent Comments ({this.props.commentCount})</h3>
        {/* Add your comment list UI here */}
      </div>
    );
  }
});

module.exports = Comments;

Quick Key Notes:

  • Props are read-only in child components—never modify this.props directly. If you need to update values, handle changes in the parent component's state and pass updated props down.
  • You can pass any data type as props: strings, numbers, objects, arrays, even functions (super useful for parent-child callback patterns!).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:38:07