ReactJS自定义三状态复选框将不显示复选标记

ReactJS custom tristate checkbox will not show checkmark

本文关键字:显示 自定义 状态 复选框 ReactJS      更新时间:2023-09-26

我正在尝试使用React创建一个三状态复选框。我正在用gulp-react 3.0.1编译,并在Chrome和Edge上进行了测试,运气不佳。目标是在to Do列表中使用复选框,并且我喜欢使用"进行中"状态,因此序列应该是:

  • 未选中复选框(空方框)
  • 点击
  • 未选中单选按钮(空圆圈)
  • 点击
  • 复选框(带复选标记的方块)
  • 重复(下一个点击回到未选中的复选框)
下面的代码实际上是:
  • 未选中复选框(空方框)
  • 点击
  • 未选中单选按钮(空圆圈)
  • 点击
  • 未选中复选框(空方块)->问题
我看到的示例表明下面的代码可能工作,但我没有运气。我已经测试了我的价值观,并尝试消除"类型"的变化而不产生任何影响。欢迎提出任何建议:
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;
        }
    }
});

changeHandler中移除evt.preventDefault();。您现在正在阻止实际选中复选框的默认行为。

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();
    }
});