为了尽可能地简化,我的目标是根据状态的大小显示x数量的选择器(在这种情况下,技术的大小是另一个的选择选项),事实是技术状态发生变化时,某些样式类就会中断。
this.state = {
formData: {
technologies: [],
}
因此,这是两个意图相同的代码块:
第一个例子:(这可行,但不是我想要的)
renderTechnologyExperienceOptions() {
return (
<div className="col-sm-6">
<select
name="experiences"
className="form-control selectpicker is-marginless"
data-style="btn"
title="Years of Expe rience"
onChange={() => console.log('New tech selected')}
>
{MockedExperience.applicantExperience.map((item: any, index: any) => (
<option id={index} value={item.value} key={index}>
{item.text}
</option>
))}
</select>
<select
name="experiences"
className="form-control selectpicker is-marginless"
data-style="btn"
title="Years of Experience"
onChange={() => console.log('New tech selected')}
>
{MockedExperience.applicantExperience.map((item: any, index: any) => (
<option id={index} value={item.value} key={index}>
{item.text}
</option>
))}
</select>
<select
name="experiences"
className="form-control selectpicker is-marginless"
data-style="btn"
title="Years of Experience"
onChange={() => console.log('New tech selected')}
>
{MockedExperience.applicantExperience.map((item: any, index: any) => (
<option id={index} value={item.value} key={index}>
{item.text}
</option>
))}
</select>
</div>
);
}
第二个示例:(这是我想要的,但是当状态更新时,它破坏了样式)
renderTechnologyExperienceOptions(technologiesLength: number) {
console.log(this.state.formData.technologies);
let visibles = 0;
if (technologiesLength == 2) {
visibles = 2;
} else if (technologiesLength == 3) {
visibles = 3;
}
let rows = [];
let options = [];
for (let index = 0; index < 5; index++) {
options.push(
<option value={MockedExperience.applicantExperience[index].value} key={index}>
{MockedExperience.applicantExperience[index].text}
</option>,
);
}
for (let index = 0; index < visibles; index++) {
rows.push(
<select
key={index}
name="experiences"
className="form-control selectpicker is-marginless"
data-style="btn btn-link"
title="Years of Experience"
onChange={() => console.log('New tech selected')}
>
{options}
</select>,
);
}
return <div className="col-sm-6">{rows}</div>;
}
现在,可以说我开始这样的初始状态(数字是某些模拟技术的ID):
this.state = {
formData: {
technologies: [5, 9, 6],
}
在这种情况下,样式将可用,但是如果您更改状态(通过选择/取消选择一种技术),样式将中断。
所以我的问题是,为什么会这样?每当技术状态发生变化而又不破坏样式时,我该如何重新渲染它? (顺便说一下,第二个示例用于,但我也尝试过使用map,结果是相同的)