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

ReactJS中向Modal组件传值遇阻及代码示例

Fixing Value Prop Passing to Your React Modal Component

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>&#36; {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 = 0 in 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:56:19