【发布时间】:2020-01-20 07:11:45
【问题描述】:
我想弄清楚我的代码是错误还是错误。我认为没有问题,但它不起作用......
我使用的代码是: https://codepen.io/cadenzah/pen/wvwYLgj?editors=0010
class ItemView extends React.Component {
constructor(props) {
super(props)
this.state = {
options: [{
id: 1,
name: "Item 1"
},
{
id: 2,
name: "Item 2"
}],
optionSelected: 2
}
}
toggleCheckbox(e) {
console.log(e.target.id)
if (this.state.optionSelected === e.target.id) {
this.setState({
optionSelected: undefined
})
} else {
this.setState({ optionSelected: e.target.id })
}
}
render() {
return (
<div className="container">
<div className="row">
<ItemList
options={this.state.options}
optionSelected={this.state.optionSelected}
toggleCheckbox={(e) => this.toggleCheckbox(e)} />
</div>
</div>
)
}
}
const ItemList = ({ options, optionSelected, toggleCheckbox }) => {
return (
<div className="col s12">
{
options.map((option, index) => (
<Item
key={index}
option={option}
checked={(optionSelected === (index + 1) ? true : false)}
toggleCheckbox={toggleCheckbox} />
))
}
</div>
)
}
const Item = ({ option, checked, toggleCheckbox }) => {
return (
<div className="card">
<div className="card-content">
<p><label htmlFor={option.id}>
<input
className="filled-in"
type="checkbox"
id={option.id}
onChange={toggleCheckbox}
checked={(checked ? "checked" : "")} />
<span>{option.id}. {option.name}</span>
</label></p>
</div>
</div>
)
}
代码说明:
React 代码,使用了materialize-css。
这是一个包含多个项目的简单复选框功能,仅限于选择一个项目。因此,如果我选中其中一个,除了我刚刚选择的项目之外的每个项目都将自动取消选中。如果我取消选中我刚刚选中的内容,则每个项目都将保持未选中状态。
核心逻辑是:在<ItemList />组件中,有一个conditional props来决定每一项是否必须被检查。它比较 id,并将 true 或 false 提交给它的孩子。 checked 组件中使用 <Item /> 组件来设置 <input> 的 checked 属性。
奇怪的是,当我在初始状态下设置默认选项时,当我刚刚运行应用程序时,检查功能按预期工作。但是如果我点击其中一个,它就不起作用了。
它有什么问题?
【问题讨论】:
-
我认为你应该尝试使用 refs,ID 不适合 react
标签: javascript reactjs checkbox materialize