[英]React - dynamic use of country-flag-icons library
We are using https://www.npmjs.com/package/country-flag-icons library that allows to use flags icon in React in this way:我们正在使用https://www.npmjs.com/package/country-flag-icons库,它允许以这种方式在 React 中使用标志图标:
import Flags from 'country-flag-icons/react/3x2'
<Flags.US title="United States" className="..."/>
But how can i use it dynamically?但是我怎样才能动态使用它呢? Because the State code is returned through services.
因为 State 代码是通过服务返回的。
I mean a some solution like this:我的意思是这样的一些解决方案:
<Flags.{myVar} title="United States" className="..."/>
EDIT This is my file:编辑这是我的文件:
import { Link } from "react-router-dom";
import Flags from "country-flag-icons/react/3x2";
const Person = ({ linkDetail, flagNationCode }) => (
<Link to={linkDetail}>
<div className="person-footer">
<div className="info">
<div className="label">{flagNationCode}</div>
<div className="value">
<Flags.US />
)}
</div>
</div>
</div>
</Link>
);
export default Person;
You need to pick out the component into a variable that starts with a capital letter and use that as the component, eg:您需要将组件选择为以大写字母开头的变量并将其用作组件,例如:
const Person = ({ linkDetail, flagNationCode }) => {
const Flag = Flags[flagNationCode];
return (
<Link to={linkDetail}>
<div className="person-footer">
<div className="info">
<div className="label">{flagNationCode}</div>
<div className="value">
<Flag />
</div>
</div>
</div>
</Link>
);
};
You can pull out the Flag you want in to a variable and then use it as a Component您可以将所需的标志拉出到变量中,然后将其用作组件
import { Link } from "react-router-dom";
import Flags from "country-flag-icons/react/3x2";
const Person = ({ linkDetail, flagNationCode }) => {
const Flag = Flags[flagNationCode];
return (
<Link to={linkDetail}>
<div className="person-footer">
<div className="info">
<div className="label">{flagNationCode}</div>
<div className="value">
<Flag />
</div>
</div>
</div>
</Link>
)};
export default Person;
For anyone having the problem: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
对于任何有问题的人:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
Try this尝试这个
import { Link } from "react-router-dom";
import Flags from "country-flag-icons/react/3x2";
const Person = ({ linkDetail, flagNationCode }) => {
const obj: Record<string, FlagComponent> = Flags;
const Flag = Flags[flagNationCode];
return (
<Link to={linkDetail}>
<div className="person-footer">
<div className="info">
<div className="label">{flagNationCode}</div>
<div className="value">
<Flag />
</div>
</div>
</div>
</Link>
)};
export default Person;
adding this conversion const obj: Record<string, FlagComponent> = Flags;
添加此转换
const obj: Record<string, FlagComponent> = Flags;
worked for me为我工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.