单击后如何处理onClick函数
How to handle the onClick function after its been clicked
我创建了一个 expandList 变量来显示点击列表。点击后它会显示列表,但我无法关闭它。
const ExpandList = ({ students }) => {
const { grades } = students;
const [isExpanded, setIsExpanded] = useState(false);
function HandleClick(index) {
if (isExpanded === index) {
return setIsExpanded(null);
}
setIsExpanded(index);
}
return (
<div className="grades">
<button onClick={HandleClick}>
{ isExpanded ? <ImMinus/> : <ImPlus/> }
</button>
{isExpanded ? (
<div className="grades">
{grades.map((grade, index) =>
<ul key={index}>Test {index + 1}: {grade}%</ul>)}
</div>
) : null}
</div>
)
};
不确定在单击后如何处理 HandleClick 函数。
切换 isExpanded 的最佳方法是取 isExpanded 的倒数
你可以这样实现:
function HandleClick(){
setIsExpanded(!isExpanded);
}
Now every time you click on the button, the method will change the state of isExpanded to its inverse value
If the value is false it will change to true and so on
这是关于 NOT 运算符的文档
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT
我创建了一个 expandList 变量来显示点击列表。点击后它会显示列表,但我无法关闭它。
const ExpandList = ({ students }) => {
const { grades } = students;
const [isExpanded, setIsExpanded] = useState(false);
function HandleClick(index) {
if (isExpanded === index) {
return setIsExpanded(null);
}
setIsExpanded(index);
}
return (
<div className="grades">
<button onClick={HandleClick}>
{ isExpanded ? <ImMinus/> : <ImPlus/> }
</button>
{isExpanded ? (
<div className="grades">
{grades.map((grade, index) =>
<ul key={index}>Test {index + 1}: {grade}%</ul>)}
</div>
) : null}
</div>
)
};
不确定在单击后如何处理 HandleClick 函数。
切换 isExpanded 的最佳方法是取 isExpanded 的倒数
你可以这样实现:
function HandleClick(){
setIsExpanded(!isExpanded);
}
Now every time you click on the button, the method will change the state of isExpanded to its inverse value
If the value is false it will change to true and so on
这是关于 NOT 运算符的文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT