英文:
How to push react elements into an array using back ticks
问题
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { addReaction } from "../features/postsSlice";
import ThumbsUp from "@mui/icons-material/ThumbUp";
import Happy from "@mui/icons-material/SentimentSatisfiedAlt";
import Sad from "@mui/icons-material/SentimentVeryDissatisfied";
import Heart from "@mui/icons-material/Favorite";
import Coffee from "@mui/icons-material/LocalCafe";
import { IconButton } from "@mui/material";
const Reactions = () => {
const reactions = useSelector((state) =>
Object.keys(state.posts[1].reactions)
);
const emojis = [];
reactions.map((reaction) => {
const capitalize = reaction[0].toUpperCase() + reaction.slice(1);
emojis.push(<IconButton>{`<${capitalize} />`}</IconButton>);
});
console.log(emojis);
return emojis;
};
export default Reactions;
英文:
I'm trying to push icons into an array by grabbing the name from data and simply adding: "<" and "/>" so that it becomes an Mui Icon.
I've renamed the imported icons to match the names in data but when I push them into my render array, all it renders is strings.
Any ideas?
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { addReaction } from "../features/postsSlice";
import ThumbsUp from "@mui/icons-material/ThumbUp";
import Happy from "@mui/icons-material/SentimentSatisfiedAlt";
import Sad from "@mui/icons-material/SentimentVeryDissatisfied";
import Heart from "@mui/icons-material/Favorite";
import Coffee from "@mui/icons-material/LocalCafe";
import { IconButton } from "@mui/material";
const Reactions = () => {
const reactions = useSelector((state) =>
Object.keys(state.posts[1].reactions)
);
const emojis = [];
reactions.map((reaction) => {
const capitalize = reaction[0].toUpperCase() + reaction.slice(1);
emojis.push(<IconButton>{`<${capitalize} />`}</IconButton>);
});
console.log(emojis);
return emojis;
};
export default Reactions;
答案1
得分: 2
你不能使用这种方式:
emojis.push(<IconButton>{`<${capitalize} />`}</IconButton>);
而是你可以使用一个对象映射来代替:
// 创建一个包含所有可能使用的元素的对象。
const MyMap = {
ThumbsUp,
Happy,
Sad,
Heart,
Coffee
};
// 然后这样使用:
const EmojiElem = MyMap[capitalize];
emojis.push(<IconButton><EmojiElem /></IconButton>);
英文:
You cannot use this way:
emojis.push(<IconButton>{`<${capitalize} />`}</IconButton>);
Instead what you can do is have an object map for all those:
// Create an object with all the possible elements you would use.
const MyMap = {
ThumbsUp,
Happy,
Sad,
Heart,
Coffee
};
// And use it this way:
const EmojiElem = MyMap[capitalize];
emojis.push(<IconButton><EmojiElem /></IconButton>);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论