【发布时间】:2015-08-13 17:54:14
【问题描述】:
我正在尝试使用 React 创建一个三态复选框。我正在使用 gulp-react 3.0.1 进行编译,并且已经在 Chrome 和 Edge 中进行了测试,没有任何运气。
目标是使用待办事项列表中的复选框,我喜欢“进行中”状态,所以顺序应该是:
- 未选中的复选框(空方块)
- 点击
- 未选中的单选按钮(空圆圈)
- 点击
- 选中的复选框(带复选标记的正方形)
- 重复(下一次点击返回未选中的复选框)
我用下面的代码实际上得到的是:
- 未选中的复选框(空方块)
- 点击
- 未选中的单选按钮(空圆圈)
- 点击
- 未选中的复选框(空方块)-> 问题
- 重复
我看到的示例表明下面的代码可能有效,但我没有运气。我已经测试了我的价值观并尝试消除“类型”的变化而没有任何影响。欢迎提出任何建议:
var TriState = React.createClass({
State: { undone: 1, inprogress: 2, done: 3 },
getInitialState: function () {
return { inputType: "checkbox", checkState: false, triState: this.State.undone };
},
render: function () {
return (
<span>
<input type={this.state.inputType} checked={this.state.checkState} onChange={this.changeHandler} />
{this.props.children}
</span>
);
},
changeHandler: function (evt) {
evt.preventDefault();
switch (this.state.triState) {
case this.State.undone:
this.setState({ inputType: "radio", checkState: false, triState: this.State.inprogress });
break;
case this.State.inprogress:
this.setState({ inputType: "checkbox", checkState: true, triState: this.State.done });
break;
case this.State.done:
this.setState({ inputType: "checkbox", checkState: false, triState: this.State.undone });
break;
}
}
});
【问题讨论】:
-
checked={this.state.checkState}尝试将真实校验状态设为'checked' -
我希望它也能正常工作,但似乎没有。使用:
<input type={this.state.inputType} checked={this.state.checkState ? "checked" : ""} onChange={this.changeHandler} />导致他在所有三种模式下都在 Inspect Element 中跟踪选中的属性(不存在):<input type="radio" data-reactid=".0.0"> -
你可能需要像facebook.github.io/react/docs/forms.html那样使用
defaultChecked
标签: javascript html reactjs react-jsx