ReactJS中向Modal组件传值遇阻及代码示例
Got it, I see the issue here! In React, functional components receive all their inputs through a single props object—you can’t pass values as direct function parameters like you’re doing right now. Let’s fix that step by step.
The Problem with Your Current Code
Your component is defined to accept a dollar parameter directly:
const AmountToPayModal = (dollar: number = 0) => ( // ... your modal JSX );
But React passes props as an object, so this won’t work when you try to pass dollar as a prop later (like <AmountToPayModal dollar={50} />). The component won’t recognize the prop because it’s looking for a direct function argument instead of a property on the props object.
Corrected Component Code
Update your component to destructure the dollar prop from the props object, and add proper TypeScript typing for the props:
// Define the props type for clarity type AmountToPayModalProps = { dollar?: number; // Optional prop with default value }; const AmountToPayModal = ({ dollar = 0 }: AmountToPayModalProps) => ( <Container> <Title> <FormattedMessage id="creditPagePayment" /> </Title> <Line /> <SectionLabel> <FormattedMessage id="creditPageNoCreditRequest" /> </SectionLabel> <AmountLabel> <span>$ {dollar}</span> </AmountLabel> {/* Rest of your modal content */} </Container> );
How to Use the Component Now
When rendering your modal, pass the dollar value as a standard React prop:
// Example usage in a parent component <AmountToPayModal dollar={125.50} />
Key Notes
- The
dollar = 0in the destructuring sets a default value, so if you don’t pass the prop, it will default to 0 (just like your original code intended). - Using a separate props type (
AmountToPayModalProps) makes your code more maintainable and gives you TypeScript’s type-checking benefits.
内容的提问来源于stack exchange,提问作者Twitter khuong291

