如何组合这两个函数(handleSelectAll和handleSelectNone)?切换(开/关)在这里不起作用,因为在大多数情况下,一些选项会被选中,所以你不知道是全部切换还是不切换,所以需要有两个独立的按钮(至少我是这么认为的)。我想的是函数可以共享
const handleSelectAll = () => {
setCategories(oldCats => oldCats.map(category => {
return {
...category,
selected: true
}
}))
}
const handleSelectNone = () => {
setCategories(oldCats => oldCats.map(category => {
return {
...category,
selected: false
}
}))
}然后是组件中的按钮:
const Categories = (props) => {
return(
<div className="categories">
<h2>Categories</h2>
<form className="check-form">
{props.categories.map(category => (
<Category key={category.id} category={category} {...props} />
))}
</form>
<button onClick={props.handleSelectAll}>
Select All
</button>
<button onClick={props.handleSelectNone}>
Select None
</button>
</div>
);
};有没有办法只为两个按钮定义一个函数?
发布于 2020-06-07 05:24:54
我通常这样做,让事情简单明了,不要太花哨:
const handleSelect = (selected = false) => {
setCategories((oldCats) =>
oldCats.map((category) => {
return {
...category,
selected,
}
})
)
}
const handleSelectAll = () => {
return handleSelect(true)
}
const handleSelectNone = () => {
return handleSelect()
}(渲染部分按原样继续)
这样做可以避免创建额外的模板函数,传递参数并在每次呈现时创建新函数
发布于 2020-06-07 05:22:28
是的。您可以使用函数包装对props.handleSelectAll和props.handleSelectNone的调用,并将新值作为参数传递:
const Categories = (props) => {
return(
<div className="categories">
<h2>Categories</h2>
<form className="check-form">
{props.categories.map(category => (
<Category key={category.id} category={category} {...props} />
))}
</form>
<button onClick={()=>props.handleSelect(true)}>
Select All
</button>
<button onClick={()=>props.handleSelect(false)}>
Select None
</button>
</div>
);
};()=>props.handleSelect(true)是一个箭头函数,它在单击时调用handleSelect
新函数将是:
const handleSelect= (newValue) => {
setCategories(oldCats => oldCats.map(category => {
return {
...category,
selected: newValue
}
}))
}发布于 2020-06-07 05:22:36
您可以使用参数使其成为一个函数,例如
const handleChangeAll = (selected) => {
setCategories(oldCats => oldCats.map(category => {
return {
...category,
selected: selected
}
}))
}然后,您可以在每个按钮中使用一个参数调用此函数,如下所示:
const Categories = (props) => {
return(
<div className="categories">
<h2>Categories</h2>
<form className="check-form">
{props.categories.map(category => (
<Category key={category.id} category={category} {...props} />
))}
</form>
<button onClick={() => props.handleChangeAll(true)}>
Select All
</button>
<button onClick={() => props.handleChangeAll(false)}>
Select None
</button>
</div>
);
};https://stackoverflow.com/questions/62238129
复制相似问题