我想讓一個按鈕在React中表現得像一個復選框,所以已經被選中/點擊的按鈕可以再次回傳其值,或者可以再次取消選擇。但我還沒有找到方法。
以下是我的代碼
const handleSelectedValue=(reason: any)=> {
setSelectedValues(item => [...item, reason]) 。
};
// If value selected then change style[/span].
const checkId = (id: number)=> {
return selectedValues.map(item => item. id).includes(id)。
};
//inside jsx.
{reasons.map(span class="hljs-params">item => {
return (
< button
key={item.id}。
className={`mr-2 mb-2 text-xs border- 2 rounded-full font-semibold border-card-primary px-3 sm。 px-5 py-2 ${checkId(item. id)?'text-white bg-base-primary opacity-75 border-none' : 'text-base-secondary'}`}'。
onClick={() => handleSelectedValue(item)}。
>
{item.cause}
</button>
);
})}
這段代碼可以作業,但選擇的值不能取消選擇。謝謝你。
uj5u.com熱心網友回復:
你必須檢查陣列中的原因是否存在。如果它存在,就將其洗掉,否則就將其添加到串列中。你總是添加它。
const handleSelectedValue = ( values) => {
setSelectedValues((item) => {
let idx = item.findIndex((itm) => itm.id == values.id) 。
if (idx !== -1) {
return item.filter(itm => itm.id !== values.id)
} else {
return [...item, values];
}
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/320707.html
標籤:
上一篇:我如何找到Firefox的日志?
