簡體   English   中英

有沒有辦法在 javascript/JSX(React 框架)中使用字符串來引用常量

[英]Is there a way to reference a constant using a string in javascript/JSX (React framework)

 import building from '../../../public/lotties/building.json' import chest from '../../../public/lotties/chest.json' import clock from '../../../public/lotties/clock.json' import creditcard from '../../../public/lotties/creditcard.json' import dnalottie from '../../../public/lotties/dna.json' import engineering from '../../../public/lotties/engineering.json' import handshake from '../../../public/lotties/handshake.json' import hospital from '../../../public/lotties/hospital.json' import map from '../../../public/lotties/map.json' import navpinsfalling from '../../../public/lotties/navpinsfalling.json' import radar from '../../../public/lotties/radar.json' import rocket from '../../../public/lotties/rocket.json' import student from '../../../public/lotties/student.json' import teacher from '../../../public/lotties/teacher.json' import tree from '../../../public/lotties/tree.json' import trophy from '../../../public/lotties/trophy.json' import virus from '../../../public/lotties/virus.json' import wallet from '../../../public/lotties/wallet.json'

我有一個 GenericLottie 組件,我想傳入一個像“錢包”這樣的道具並引用導入的常量。

 const animData = this.props.name; // const animData = {this.props.name}; // const animData = `${this.props.name}`;

我已經嘗試了上述所有代碼行,但都不起作用。 很明顯,我需要查看字符串文字及其工作方式。 我的問題有解決方法嗎? 如果沒有,我可以通過並單獨編寫每個代碼,我不想這樣做。

你想做的是這個嗎? 使用功能組件,而不是階級寫的,所以沒有必要為this引用道具時。

SomeOtherComponent.js

import wallet from '../../../public/lotties/wallet.json';
import GenericLottie from '../../wherever';

const SomeOtherComponent = () => {
  return <GenericLottie name={wallet} />;
};

GenericLottie.js

const GenericLottie = (props) => {
  // This should be the 'wallet' you imported in the parent component!
  const animData = props.name;

  ...
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM