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

React组件传参问题:Section调用Title时props未定义如何解决?

Solution: Fix 'props is not defined' Error & Make Components Flexible

Absolutely, you can definitely achieve this! Let's break down the issue and fix it step by step.

Why the Error Happens

Your current Section component only destructures children from its props, but you're trying to reference props.sectionText inside the component—since you didn't define props as a parameter (you used ({ children }) instead), JavaScript throws the 'props is not defined' error.

Fixed Section Component Code

You have two straightforward ways to fix this:

Option 1: Destructure both sectionText and children

This keeps the component concise and explicit about the props it accepts:

import React from "react"
import sectionStyles from "./section.module.css"
import Title from "../title/title"

export default ({ sectionText, children }) => (
  <div className={sectionStyles.container}>
    <Title titleText={sectionText} />
    {children}
  </div>
)

Option 2: Use the full props object

If you prefer to keep the props as a single object, just define props as the parameter:

import React from "react"
import sectionStyles from "./section.module.css"
import Title from "../title/title"

export default (props) => (
  <div className={sectionStyles.container}>
    <Title titleText={props.sectionText} />
    {props.children}
  </div>
)

Ensure Title Works Independently

To make sure your Title component can be used both on its own and inside Section, just ensure it properly accepts the titleText prop. Here's a robust example (add a default value to avoid issues if no prop is passed):

import React from "react"
// Add your Title styles here if needed

export default ({ titleText = "" }) => (
  <h2 className="title-class">{titleText}</h2>
)

Test the Usage

Now both use cases will work perfectly:

  • Independent Title: <Title titleText="About My Projects" />
  • Title inside Section:
<Section sectionText="Skills">
  {/* Your skills content goes here */}
  <p>JavaScript, React, CSS</p>
</Section>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:41:29