我正在尝试做什么,当单击按钮时,在 onclick 时它的变体( Material ui 按钮应从概述更改为包含)或者只是其背景应更改。 (请不要建议使用 onFocus 属性,因为这些是另一个组件中的另一个按钮,单击时焦点会丢失。所以 onFocus 不是我的选择)。我在这里附上我的方法,你可以更改它(因为我的方法无论如何都不起作用,它无限期地将状态更改为 true)
const [clicked, setClicked] = useState(false);
const categoryChangedHandler = (e) => {
setCategory(e);
};
{categories.map((category, index) => {
console.log("catogoried.map called and categories= " + category);
return <Button className="CategoryButton"
variant={clicked ? "contained" : "outlined"}
color="primary"
value={category}
onClick={() => {
categoryChangedHandler(category);
setClicked(true);
}}
style={{ textAlign: 'center' }}
>
{category}
</Button>
})
}
最佳答案
如果您想根据其类别显示不同的颜色基础,您可能需要根据状态更改变体(无论是否选择)。
示例
const categories = ['apple', 'banana', 'mango']
const App = () => {
const [ selected, setSelected ] = useState([])
const onClick = (value) => {
//this is a toggle to add/remove from selected array
if (selected.indexOf(value) > -1) {
//if exist, remove
setSelected( prev => prev.filter( item => item !== value )
} else {
//add to the selected array
setSelected( prev => [ ...prev, value ] )
}
}
return <div>
{categories.map((category, index) => {
return <Button className="CategoryButton"
/* if the category had been selected, show contained */
variant={ selected.indexOf(category) > -1 ? "contained" : "outlined"}
color="primary"
value={category}
onClick={() => {
onClick(category);
}}
style={{ textAlign: 'center' }}
>
{category}
</Button>
})
}</div>
}
上面的示例保留了一组选定的类别。当然,如果您只想允许每次点击时选择ONE,那么您可以使用setSelected(value)
(其中value是类别)而不是数组name),然后在您的按钮组件中使用
variant={ selected === category ? 'contained' : 'outlined' }
记住更改您的使用状态以使用字符串而不是数组
const [ selected, setSelected ] = useState('') //enter a category name if you want it to be selected by default
关于javascript - 我想仅在reactjs中更改单击按钮(onClick)的变体或背景。我怎样才能实现它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67042176/