我正在 React 中创建一个类似向导的表单。我希望它仅在用户在上一个下拉列表中选择一个选项时才显示另一个选择。目前我的选择有效,但我在这里使用了很多 useState 钩子。由于最终我希望有大约 10 个选择,我认为多达 10 个 useStates 可能不是最佳选择。您能否查看我的代码并给我一些提示以使其变得更好/解释为什么这样的更改会使它变得更好?
下面我发布我的代码,它在带有 bootstrap 4.2.1 和 react-select 2.2.0 的代码沙箱中工作:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import Select from "react-select";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.css";
const options1 = [
{ label: "1", value: 1 },
{ label: "2", value: 2 }
];
const options2 = [
{ label: "3", value: 3 },
{ label: "4", value: 4 }
];
const options3 = [
{ label: "5", value: 5 },
{ label: "6", value: 6 }
];
const options4 = [
{ label: "7", value: 7 },
{ label: "8", value: 8 }
];
const App = () => {
const [showSecond, setShowSecond] = useState(false);
const [showThird, setShowThird] = useState(false);
const [showFourth, setShowFourth] = useState(false);
const [showButton, setShowButton] = useState(false);
const renderSecond = () => {
if (showSecond) {
return (
<div className="form-group row mt-2">
<label className="col-4">Select 2</label>
<Select
onInputChange={updateSecond}
className="col-8"
options={options2}
/>
</div>
);
}
};
const renderThird = () => {
if (showThird) {
return (
<div className="form-group row mt-2">
<label className="col-4">Select 3</label>
<Select
onInputChange={updateThird}
className="col-8"
options={options3}
/>
</div>
);
}
};
const renderFourth = () => {
if (showFourth) {
return (
<div className="form-group row mt-2">
<label className="col-4">Select 4</label>
<Select
onInputChange={updateFourth}
className="col-8"
options={options4}
/>
</div>
);
}
};
const updateFirst = () => {
// update some data
setShowSecond(true);
};
const updateSecond = () => {
// update some data
setShowThird(true);
};
const updateThird = () => {
// update some data
setShowFourth(true);
};
const updateFourth = () => {
// update some data
setShowButton(true);
};
return (
<div className="container">
<div className="col-12">
<form className="form">
<div className="form-group row mt-2">
<label className="col-4">Select 1 </label>
<Select
className="col-8"
onInputChange={updateFirst}
options={options1}
/>
</div>
{renderSecond()}
{renderThird()}
{renderFourth()}
</form>
</div>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
在我学习 React 的过程中,每一个建议都将不胜感激!