gpt4 book ai didi

javascript - react 组件: Need to format an address from an API response and pass it to a component with copy to clipboard functionality

转载 作者:行者123 更新时间:2023-12-02 21:56:32 26 4
gpt4 key购买 nike

我有一个 react 组件,它显示一个地址,旁边有一个复制到剪贴板图标。

返回的地址包含 5 个元素:地址 1、地址 2、城市、州和邮政编码

当我在前端显示元素时,我可以根据它们是否存在有条件地渲染它们。但是我不确定如何将其传递给我的 CopyButton。

我开始编写一个格式化程序,但在传递格式化地址时遇到了问题。

这是我当前的格式化程序代码以及显示的字符串和 CopyButton 组件以供引用:

Formatter
    const formatAddress = (addressLine1: string, addressLine2: string, city: string, state: string, zip5: string ) => {
let formattedAddress = ''
address2 ? formattedAddress = `${addressLine1} ${addressLine2}, ${city}, ${state} ${zip5}` : formattedAddress = `${addressLine1}, ${city}, ${state} ${zip5}`
return formattedAddress
}
<p> element with address and CopyButton
 {address1
? (
<p data-testid="address">
{address1}
{address2 && `, ${address2}`}
{city && `, ${city}`}
{state && `, ${state}`}
{zip && ` ${zip.substring(0, 5)}`}
{formatAddress(address1, address2, city, state, zip)}
<ButtonCopyText
a11yText="Copy Address"
textToCopy={formattedAddress}
/>
</p>
) : (
<p data-testid="no-address">--</p>
)
}

最佳答案

        let formattedAddress = ''
address2 ? formattedAddress = `${addressLine1} ${addressLine2}, ${city}, ${state} ${zip5}` : formattedAddress = `${addressLine1}, ${city}, ${state} ${zip5}`

可能是这个

const formattedAddress =
`${addressLine1}${addressLine2 ? ` ${addressLine2}` : ''}, ${city}, ${state} ${zip5}`.trim();

此外,你永远不会定义 formattedAddress当你去使用它作为传递给你的<ButtonCopyText />的 Prop 时成分。您可以在 prop 赋值中调用该函数,或者将函数的返回值分配到 JSX 之外的某个变量中。

关于javascript - react 组件: Need to format an address from an API response and pass it to a component with copy to clipboard functionality,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59994214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com