React组件传参问题:Section调用Title时props未定义如何解决?
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

