我有以下内容:
import React, {
Fragment,
useState
} from "react";
import PropTypes from "prop-types";
import {
connect
} from "react-redux";
import {
Link,
withRouter
} from "react-router-dom";
const ChooseRole = () => {
// const [role, setRole] = useState({
// business: false,
// jobSeeker: false
// });
const [business, toggleBusiness] = useState(false);
const [jobSeeker, toggleJobSeeker] = useState(false);
const onClick = (e, roleType) => {
switch (roleType) {
case "business":
toggleBusiness(!business);
if (business === true) {
toggleJobSeeker({
jobSeeker: false
});
}
break;
case "jobSeeker":
toggleJobSeeker(!jobSeeker);
if (jobSeeker === true) {
toggleBusiness({
business: false
});
}
break;
}
};
return (
<Fragment>
<h1>First thing's first</h1>
<h3 className="mt-4">I'm a...</h3>
<h3
name="business"
className={business === true ? "text-primary" : ""}
style={{ cursor: "pointer" }}
onClick={e => onClick(e, "business")}
>
Business
</h3>
<h3
name="jobSeeker"
className={jobSeeker === true ? "text-primary" : ""}
style={{ cursor: "pointer" }}
onClick={e => onClick(e, "jobSeeker")}
>
Talent
</h3>
</Fragment>
);
当我单击呈现的任何一个h3
元素时,className没有被正确添加。点击例如业务后,该h3的文本应变为橙色。再次单击它应将其变回黑色。如果文字业务为橙色,则单击“人才”应将“人才”文本变为橙色,然后将“业务”文本变为黑色。但是由于某种原因,单击“业务”然后单击“人才”会使它们两个都变为橙色。再次单击任意一个,将它们都变回黑色。我不确定自己在做什么错,我在某处有逻辑错误吗?
答案 0 :(得分:3)
您的问题是,您正在状态中设置对象而不是布尔值。另外,您需要引用正确的变量。无需检查业务是否正确并将Jobseeker设置为false ..只需在业务切换中检查Jobseeker是否为真
switch (roleType) {
case "business":
toggleBusiness(!business);
if (jobSeeker === true) {
toggleJobSeeker(false);
}
break;
case "jobSeeker":
toggleJobSeeker(!jobSeeker);
if (business === true) {
toggleBusiness(false);
}
break;
}