如何在Material Ui中的复选框内添加字母或文本



我想制作像给定图像一样的复选框,我指的是里面有任何文本的圆形复选框。提前谢谢。点击此处查看图像

使用MUI Avatar

const [isSelected , setIsSelected] = useState(false)


<Avatar sx={{ bgcolor: `${isSelected?'#1a73e8':'grey'}` }} onClick={() => setIsSelected(!isSelected)}>M</Avatar>

编辑
对于动态:

使用对象数组:

const [weekdays , setWeekDays] = useState([{
day:'S',
select:false
},
{
day:'M',
select:false
},
{
day:'T',
select:false
},
{
day:'W',
select:false
},
{
day:'T',
select:false
},
{
day:'F',
select:false
},
{
day:'S',
select:false
}])


<Stack direction="row" spacing={2}>
{weekdays.map((day, i) => (
<Avatar
sx={{
bgcolor: `${day.select ? "#1a73e8" : "grey"}`,
height: "25px",
color: "white",
width: "25px",
fontSize: "12px"
}}
onClick={() => handleSelect(day , i)}
alt="Remy Sharp"
>
{day.day}
</Avatar>
))}
</Stack>


const handleSelct = (ob, ind) => {
const newArr = weekdays.map((obj, i) => {
if (i === ind) {
return { ...obj, select: !obj.select };
}
return obj;
});
setWeekdays(newArr);
};

在您的情况下,a更喜欢使用IconButton和useState来处理

const [alarmcheck,setAlarmCheck]=useState(false)
const [cartcheck,setCartCheck]=useState(false)
<IconButton color="secondary" aria-label="alarm" sx={alarmcheck&& 
{backgroundColor:red}} onClick={ (prev)=>setsetAlarmCheck(!prev)}>
<AlarmIcon />
</IconButton>
<IconButton color="primary" aria-label="add to shopping cart" onClick={ 
(prev)=>setsetCartCheck(!prev)}  sx={cartcheck&&{backgroundColor:green}}>
<AddShoppingCartIcon />
</IconButton>

试试

通过将文本内容呈现为跨度并将道具传递给基于活动索引的样式组件,解决了类似的问题。

我正在使用MUI,但无法找到添加文本的方法(类似于您所面临的问题(。所以我尝试了这种方法。

注意:我没有使用MUI。唯一附加的是,我使用的是样式化组件。如果您使用的是emotion/styled,那应该没问题

以下是我的实施。也许这可能有助于

import React from 'react';
import './style.css';
import styled from 'styled-components';
const weekdaysLabel = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const PayoutWeekDaysStyled = styled.span<any>`
width: 50px;
height: 50px;
border-radius: 30px;
font-size: 16px;
margin: 1rem;
text-align: center;
line-height: 50px;
color: ${(props: any) => (props.isActive ? '#fff' : '#000')};
background-color: ${(props: any) => (props.isActive ? '#0094CD' : '#f4f5f7')};
&:hover {
background-color: ${(props: any) =>
props.isActive ? '#0094CD' : '#f4f5f7'};
cursor: pointer;
color: ${(props: any) => (props.isActive ? '#fff' : '#000')};
}
`;
export default function App() {
const [weekdays, setWeekdays] = React.useState([]);
const handleClick = (item) => {
if (weekdays.includes(item)) {
const updatedWeekdays = weekdays.filter((day) => day !== item);
setWeekdays(updatedWeekdays);
} else {
setWeekdays([...weekdays, item]);
}
};
return (
<div style={{ display: 'flex', gap: '1rem' }}>
{weekdaysLabel.map((item, index) => (
<PayoutWeekDaysStyled
key={index}
isActive={weekdays.includes(item)}
onClick={() => {
handleClick(item);
}}
>
{item}
</PayoutWeekDaysStyled>
))}
</div>
);
}

最新更新