我正在尝试使用React创建一个三态复选框。我正在使用gulp-react 3.0.1进行编译,并且已经在Chrome和Edge中进行了测试,没有运气。
目标是使用待办事项列表中的复选框,我希望有一个"正在进行中"状态,所以序列应该是:
我实际得到的代码是:
我见过的示例表明下面的代码可能有效,但我没有运气。我已经测试了我的价值观并试图消除“#type;'没有任何影响。欢迎提出任何建议:
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;
}
}
});
答案 0 :(得分:2)
从evt.preventDefault();
中删除changeHandler
。
您现在正在阻止实际选中复选框的默认行为。
答案 1 :(得分:0)
var TriState = React.createClass({
Mode: { undone: 1, inprogress: 2, done: 3 },
getInitialState: function () {
return { mode: this.Mode.undone };
},
render: function () {
return (
<span>
<input ref="triState" type={this.state.mode === this.Mode.inprogress ? "radio" : "checkbox"} onChange={this.changeHandler} />
<span onMouseUp={this.clickHandler}> {this.props.children}</span>
</span>
);
},
changeHandler: function (evt) {
switch (this.state.mode) {
case this.Mode.undone:
this.setState({ mode: this.Mode.inprogress });
evt.preventDefault();
break;
case this.Mode.inprogress:
this.setState({ mode: this.Mode.done });
break;
case this.Mode.done:
this.setState({ mode: this.Mode.undone });
break;
}
},
clickHandler: function () {
React.findDOMNode(this.refs.triState).click();
}
});