本文介绍了React JS-为Ant设计开关添加唯一键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在如何向循环下的交换机添加唯一键方面遇到问题.
I am having a problem on how to add a unique key to the switch that is under my loop.
实际输出:每当我单击一个开关时,所有开关也都在切换.
Actual Output: Whenever I click one switch, all switches are toggling too.
预期结果:一个开关必须根据我选择的开关而不是其他开关进行切换
Expected Result: One switch must toggle depends on what switch I selected and not the other switches
这是我的代码:
let keys;
let output = [];
for (let i = 0; i < info.length; i++) {
keys = {
...info[i],
key: i,
actionIndex: (
<div>
<Switch
checked={isSwitchToggle ? true: false}
onClick={()=> {
handleSwitch(
info[i],
handleChangeSwitch,
)
}} />
</div>
),
};
output.push(keys);
}
return output;
这是切换 isSwitchToggle
状态
handleChangeSwitch = () => {
const { isSwitchToggle } = this.state
this.setState({
isSwitchToggle: !isSwitchToggle,
})
}
顺便说一句,我使用Ant设计开关.感谢您的帮助
Im using Ant design switch by the way. Thanks for the help
推荐答案
Here is how to handle an individual switch. Do change the demo code as per your demand.
应用
class App extends Component {
state = {};
render() {
let info = [
{ id: 1, name: "a", isSwitchToggle: true },
{ id: 2, name: "b", isSwitchToggle: false },
{ id: 3, name: "c", isSwitchToggle: true }
];
let output = [];
for (let i = 0; i < info.length; i++) {
output.push(<SingleSW data={info[i]} />);
}
let switches =
output.length !== 0 && output.map((row, i) => <div key={i}>{row}</div>);
return <div>{switches}</div>;
}
}
SingleSW (单个开关功能组件)
const SingleSW = ({ data }) => {
const [switchToggle, setSwitchToggle] = useState(data.isSwitchToggle);
const onChange = checked => {
setSwitchToggle(checked);
};
return (
<div className="wrapper">
<Switch checked={switchToggle} onChange={onChange} />
<span> {data.name}</span>
</div>
);
};
这篇关于React JS-为Ant设计开关添加唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!