简体   繁体   English

如何在 React (JSX) 中连接动态值

[英]How to concatenate dynamic values in React (JSX)

With my endpoint I can fetch data and set currency as a parameter, so that data received is converted into the currency user chooses.通过我的端点,我可以获取数据并将货币设置为参数,以便将接收到的数据转换为用户选择的货币。 I am passing the currency as a prop into a component that renders that data The problem is that I am having trouble displaying the price dynamically.我将货币作为道具传递给呈现该数据的组件 问题是我无法动态显示价格。 I am not sure how can I concatenate the JSX correctly... { crypto.quote.${currency}.price.toFixed(2) } just prints the string.我不确定如何正确连接 JSX... { crypto.quote.${currency}.price.toFixed(2) } 只是打印字符串。 Hardcoding the currency (USD, EUR etc) renders the price, but I want it to be dynamic.硬编码货币(美元、欧元等)会呈现价格,但我希望它是动态的。 Thank you, help please :)谢谢,请帮忙:)

import React from 'react';
import { Link } from "react-router-dom"

const Crypto = ({ crypto, currency }) => {

    return <>
        <tr>
            <td>{crypto.cmc_rank}</td>
            <td>
                <Link to={{
                    pathname: `/crypto/${crypto.id}`,
                    state: crypto
                }}>
                    {crypto.name}
                </Link>
            </td>
            <td>{crypto.symbol}</td>
            <td>
                {`crypto.quote.${currency}.price.toFixed(2)`}

            </td>
            <td>{crypto.quote.USD.percent_change_24h}</td>
            <td>
                {crypto.quote.USD.market_cap.toString().slice(0, 3) + "B"}
            </td>
        </tr>

    </>
}

export default Crypto;

Instead of Template Literals which is the reason why you have a string printed out there, you can simply evaluate the values.您可以简单地评估值,而不是模板文字(这是您在那里打印字符串的原因)。 See below my suggested solution as:请参阅下面我建议的解决方案:

<td>
    {crypto.quote[currency].price.toFixed(2)}
</td>

Check below a working example:检查下面的工作示例:

 const crypto = { quote: { USD: { price: 120.1122 } } } const currency = 'USD' const result = crypto.quote[currency].price.toFixed(2) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM