0Pricing
Next.js 15 Fullstack Web Apps · 课时

属性与组件通信

掌握使用属性在父组件和子组件之间传递数据的方法,以构建灵活的用户界面。

属性与组件通信 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to Component Props

In React, props (short for properties) are how you pass data from a parent component down to a child component.

Think of them like arguments to a function. They allow you to make your components reusable and dynamic, displaying different information based on the data they receive.

Unidirectional Data Flow

One of the core principles of React is unidirectional data flow. This means data always moves in one direction: from parent to child.

  • Parent components own and manage data.
  • They pass this data down to their children using props.
  • Child components receive props and render content based on them.
  • Children cannot directly modify the props they receive; props are read-only.

Your First Prop

Let's see how to pass a simple string prop. We'll create a Greeting component that receives a name prop.

Notice how App (parent) passes name="Alice" to Greeting (child).

import React from 'react';
import ReactDOM from 'react-dom/client';

// Child Component
function Greeting(props) {
  // Access the 'name' prop using props.name
  return <p>Hello, {props.name}!</p>;
}

// Parent Component
function App() {
  return (
    <div>
      <Greeting name="Alice" />
      <Greeting name="Bob" />
    </div>
  );
}

// Render the App component
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Passing Different Data Types

Props aren't just for strings! You can pass numbers, booleans, arrays, and objects. When passing non-string values, wrap them in curly braces {}.

This example shows a ProductCard receiving various data types.

import React from 'react';
import ReactDOM from 'react-dom/client';

function ProductCard(props) {
  return (
    <div style={{ border: '1px solid gray', padding: '10px', margin: '10px' }}>
      <h3>{props.productName}</h3>
      <p>Price: ${props.price.toFixed(2)}</p>
      <p>In Stock: {props.inStock ? 'Yes' : 'No'}</p>
      <p>Features:</p>
      <ul>
        {props.features.map((feature, index) => (
          <li key={index}>{feature}</li>
        ))}
      </ul>
    </div>
  );
}

function App() {
  const laptop = {
    name: "Super Laptop",
    price: 1200.50,
    available: true,
    specs: ["Fast CPU", "16GB RAM", "512GB SSD"]
  };

  return (
    <div>
      <ProductCard
        productName={laptop.name}
        price={laptop.price}
        inStock={laptop.available}
        features={laptop.specs}
      />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Destructuring Props for Clarity

Accessing props like props.name can get repetitive. A cleaner way is to use object destructuring directly in your component's function signature.

This makes your code more readable by explicitly showing which props a component expects.

import React from 'react';
import ReactDOM from 'react-dom/client';

// Before: function Greeting(props) { return <p>Hello, {props.name}!</p>; }
// After destructuring:
function Greeting({ name }) {
  return <p>Hello, {name}!</p>;
}

function App() {
  return (
    <div>
      <Greeting name="Charlie" />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

The Special 'children' Prop

React has a special prop called children. This prop automatically contains whatever content you pass between a component's opening and closing tags.

It's perfect for creating wrapper components like cards, layouts, or modals.

import React from 'react';
import ReactDOM from 'react-dom/client';

function Card({ title, children }) {
  return (
    <div style={{ border: '1px solid #ddd', padding: '15px', margin: '10px', borderRadius: '8px' }}>
      <h4>{title}</h4>
      <div style={{ marginTop: '10px' }}>
        {children}
      </div>
    </div>
  );
}

function App() {
  return (
    <div>
      <Card title="User Profile">
        <p>Name: <b>Jane Doe</b></p>
        <p>Email: jane@example.com</p>
        <button>Edit Profile</button>
      </Card>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Child to Parent: Callback Props

Since data flows down, how does a child component tell its parent something happened (e.g., a button was clicked)? You pass a function as a prop!

The child calls this function, and the parent can then react to the event. This is often called a 'callback prop'.

import React from 'react';
import ReactDOM from 'react-dom/client';

// Child Component
function MyButton({ onClick, label }) {
  return (
    <button onClick={onClick}>
      {label}
    </button>
  );
}

// Parent Component
function App() {
  const handleButtonClick = () => {
    alert("Button clicked inside the child component!");
  };

  return (
    <div>
      <p>Parent says: Click the button below!</p>
      <MyButton onClick={handleButtonClick} label="Trigger Parent" />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

When Props Aren't Enough

While props are powerful, passing them through many layers of nested components can become cumbersome. This is known as prop drilling.

If you find yourself passing the same prop through 3+ components just to reach a deeply nested child, it might be a sign to consider other patterns like React Context API or state management libraries (which we'll cover in future lessons!).

Prop Challenge

Which of the following statements about React props are true?

Recap: Props, Your UI's Data

You've mastered props, a fundamental concept in React!

  • Props pass data from parent to child components.
  • Data flow is unidirectional; children cannot modify props.
  • You can pass various data types (strings, numbers, objects, functions).
  • Destructuring props makes your code cleaner.
  • The children prop allows flexible content embedding.
  • Callback props enable child-to-parent communication.

Props are the backbone of building dynamic and reusable React components. Keep practicing, and you'll be building complex UIs in no time!

常见问题解答

「属性与组件通信」课时是免费的吗?

是的 — 「属性与组件通信」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

「属性与组件通信」这节课中我会学到什么?

掌握使用属性在父组件和子组件之间传递数据的方法,以构建灵活的用户界面。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack Web Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「属性与组件通信」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. React 组件与 JSX
  2. 使用 Hooks 管理状态
  3. 属性与组件通信
  4. 渲染列表、键与条件式 UI
← 返回 Next.js 15 Fullstack Web Apps