【问题标题】:Change currency state from a default const object从默认 const 对象更改货币状态
【发布时间】:2020-10-31 08:19:28
【问题描述】:

我想从我的 defaultMaskOptions 组件中更改货币前缀状态,因为稍后这将用作另一个组件中的道具。这是代码:

const defaultMaskOptions = {
prefix: '$',
suffix: '',
includeThousandsSeparator: true,
thousandsSeparatorSymbol: '',
allowDecimal: true,
}

const CurrencyInput = ({ maskOptions, ...inputProps }) => {
const currencyMask = createNumberMask({
...defaultMaskOptions,
...maskOptions,
})

 return <MaskedInput mask={currencyMask} {...inputProps} />
}

【问题讨论】:

  • 这应该是您将掩码传递给 MaskedInput 的方式

标签: javascript reactjs input components currency


【解决方案1】:

您需要创建前缀状态而不是 const 对象。

使用功能组件可以这样:

const [prefix, setPrefix] = React.useState('$')

像这样将它传递给 MaskedInput:

return <MaskedInput mask={currencyMask} prefix={prefix} {...inputProps} />

使用当前组件中某处的 onClick 处理程序更新前缀,如下所示:

const handleCurrencyChange = (event) => {
   setPrefix(event.target.value)
}

当父级中的状态更新时,它会在 MaskedInput 组件中重新渲染。

另外

如果您需要在 MaskedInput 中更新 prefix,您可以像任何其他 prop 一样传入 setPrefix,并使用它来更新状态,就像我在上面显示的父级中一样。

【讨论】:

    猜你喜欢
    • 2012-05-08
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    相关资源
    最近更新 更多