如何在React中使一个变量成为常量名



我试图在用户名字的第一个字母的条件下呈现单个字母的配置文件图标。

EX: sam = 'S'

我已经为每个字母创建了一个const,并想渲染它们,但我不确定如何将字母变量应用到组件。

我的代码是这样的

function foo() {
var obj = JSON.parse(localStorage.getItem('user'));
let firstName = obj[0].firstName;
let letter = firstName.charAt(0).toUpperCase();
render ( <S /> )
}
const S = () =>
<span className="profile-icons" style={{'backgroundPosition': '0 -576px',}} />
...
A-Z

您可以简单地使用props实现它. 只是一定要给它一个正确的样式。

const ProfileIcon = ({ letter }) => {
return (
<span className="profile-icons" style={{'backgroundPosition': '0 -576px',}}>
{letter}
</span>
);
}
render (<ProfileIcon letter={letter} />)

reactjs.org/docs/components-and-props.html

最新更新