有人可以告诉我一种更好的方式来运行这些按钮功能的方法。在下面的示例中,我有两个按钮,但是在实际版本中,我有很多按钮。这变得难以管理。我遇到了编码员的困扰,似乎无法找出一种优雅的解决方案。有帮助吗?
function DashboardPage() {
const [showCandidatesComponent, setShowCandidatesComponent] = useState(false);
const [showEmployersComponent, setShowEmployersComponent] = useState(true);
function handleViewCandidatesButton(e) {
e.preventDefault();
setShowCandidatesComponent(true);
setShowEmployersComponent(false);
}
function handleViewEmployersButton(e) {
e.preventDefault();
setShowEmployersComponent(true);
setShowCandidatesComponent(false);
}
return (
<div className="row flex-xl-nowrap">
<button
type="button"
onClick={handleViewCandidatesButton}
className="btn btn-link btn-block text-left"
>
Candidates
</button>
<button
type="button"
onClick={handleViewEmployersButton}
className="btn btn-link btn-block text-left"
>
Employers
</button>
<main>
{showCandidatesComponent ? <Candidates /> : null}
{showEmployersComponent ? <Employers /> : null}
</main>
</div>
);
}
答案 0 :(得分:1)
您可以为页面创建索引系统,并在HTML属性(例如name
)上添加与每个页面的按钮相对应的索引号。
这样做,可以解决让每个按钮的onClick
处理函数执行的问题:
setShowCandidatesComponent(true), setShowEmployersComponent(false), ...
由于只有一个视图可以对应一个索引号,因此您无需每次单击按钮都处理所有布尔值。
现在,您的仪表板组件上可以有一个通用按钮处理程序,该处理程序从event.target.name
中检索索引并更新状态。只需确保将event.target.name
解析为整数即可,因为它是一个字符串。
DashboardPage.js
const DashboardPage = props => {
// viewIndex refers to the index in the views array that will be rendered.
const [viewIndex, setViewIndex] = useState(0);
// I attached the index to the "name" attribute for each button.
const handleViewChange = event => setViewIndex(+event.target.name);
// Get the button labels for each view.
const buttonLabels = views.map(view => view.name);
return (
<div>
{/* Render out each button here. Assign index to name and attach
handleViewChange */}
{buttonLabels.map((view, i) => (
<button key={i} name={i} onClick={handleViewChange}>
{view}
</button>
))}
{/* This will render the component for the specified view index. */}
{views[viewIndex].component}
</div>
);
};
// Create a map of button name to corresponding component.
const views = [
{ name: "Employers", component: <Employers /> },
{ name: "Employees", component: <Employees /> },
{ name: "Contractors", component: <Contractors /> },
{ name: "Candidates", component: <Candidates /> }
];