我可以在 React JS 中对这段代码使用 DRY Concept 吗?

Can I use DRY Concept for this code in React JS?


import React from "react";
import { Chip, Box } from '@mui/material';

const Browse = () => {

const [chip, setChip] = React.useState("all")

const handleClick = (event)=>{
  setChip(event.target.textContent);
  console.log(chip)
}


return (
  <Box mx={2} >
    <Box mt={2} sx={{display:"flex", gridGap:"20px", flexWrap:"wrap"}} >

    <Chip label="Price" sx={{color:"#FF005E"}}  onClick={handleClick} />
    <Chip label="Type of place" sx={{color:"#FF005E"}}  onClick={handleClick} />

    <Chip label="all"      variant={ "all" === chip ? "filled": "outlined" } onClick={handleClick} />
    <Chip label="mountain" variant={"mountain" === chip ? "filled": "outlined" } onClick={handleClick} />
    <Chip label="beach" variant={  "beach"  === chip ? "filled": "outlined" } onClick={handleClick} />
    <Chip label="island" variant={ "island" === chip ? "filled": "outlined" } onClick={handleClick} />
    <Chip label="desert" variant={ "desert" === chip ? "filled": "outlined" } onClick={handleClick} />
    <Chip label="plain" variant={  "plain"  === chip ? "filled": "outlined" } onClick={handleClick} />

    </Box>
  </Box>
);
};

export default Browse;

任何人都可以帮助我,我的代码需要简单的 DRY 概念。 我想用“meterial-ui”芯片组件做一些小动画。 所以我一次又一次地编写相同的代码。 所以,请任何人解决这个问题...... 谢谢 :)

您可以提取创建 Chip

的方法
const createChip = (label) => <Chip label={label} variant={ label === chip ? "filled": "outlined" } onClick={handleClick} />

然后这样称呼它

{createChip("all")}
{createChip("plain")}
...

或创建数组

{["all", "plain"].map(createChip)}

但要确保每个项目都有一个键

<Chip key={label} ...

使用变体数组然后映射:

  const chips = ["all","mountain","beach","island","desert","plain"]
    .map(variant => (
       <Chip
          key={variant}
          label="all"
          variant={ variant === chip ? "filled": "outlined" } 
          onClick={handleClick} />
    ))

然后您可以在下面的 JSX 中使用 {chips}

文档:https://reactjs.org/docs/lists-and-keys.html