【发布时间】:2020-09-10 02:44:50
【问题描述】:
我在 React 中有一个相对简单的 Bootstrap 卡片布局,其中包含多张卡片,每张卡片上都有一个切换开关。但是,无论按下哪个切换开关,它总是被调用的第一张卡的处理函数(因此第一个切换改变状态)。我不明白他们为什么不调用自己的函数。
我的结构是卡片组有多个卡片孩子,每个卡片都有一个拨动开关孩子,例如卡片组 -> 卡片 -> 切换
卡片组
class CardDeck extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{title: 'Cat 1'},
{title: 'Cat 2'},
{title: 'Cat 3'}
]
}
}
render() {
return (
<div class="card-deck">
{this.state.data.map((item, index) =>
<Card
key={index}
title={item.title}
index={index}
id={index}
/>
)}
</div>
);
}
}
卡片
class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false,
}
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState({
checked: !this.state.checked,
});
}
render() {
return (
<div class="card" key={this.props.index}>
<div class="card-body">
<h5 class="card-title">{this.props.title}</h5>
<p class="card-text">Text</p>
</div>
<div class="card-footer">
<Toggle checkStatus={this.state.checked} onChange={this.handleChange} key={this.props.index} />
</div>
</div>
);
}
}
切换
class Toggle extends React.Component{
render() {
return (
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitches" onChange={this.props.onChange} checked={this.props.checkStatus} />
<label class="custom-control-label" for="customSwitches">Label</label>
</div>
)
}
}
【问题讨论】:
-
我看不出这段代码有问题。你能把它放在沙箱里并重现它吗?
-
我可以看到的语法错误在 Card 组件中。 handleChange --> handleChange() handleChange { this.setState({ check: !this.state.checked, }); } 还有 class= "card-页脚”。我不确定这个复制粘贴是否错误?
-
我试图让它在沙箱中工作,但到目前为止失败了。
-
它们都是复制/粘贴错误,但谢谢。我已经编辑修复这些问题。
-
所以我让它在沙箱中工作并且无法重现该问题。在进一步调查中,问题似乎在于我实际上正在使用引导切换类“custom-control-input”。当我删除它时,问题就消失了。有任何想法吗?我可能会提出一个更具体的新问题...
标签: javascript reactjs twitter-bootstrap