首页 > 解决方案 > ReactJs 设置自定义引导复选框的不确定状态

问题描述

我已经制作了这个复选框,它应该是一个“三态复选框”,它不仅将不确定状态用作“视觉值”,而且还用作“真实”值。如果我只使用标准复选框,它工作得很好,但如果我使用引导自定义复选框,它就不再工作了,因为ReactDOM.findDOMNode(this).indeterminate无法访问该复选框。所以ReactDOM.findDOMNode(this).indeterminate = true;不设置不确定为true.

这是我的组件:

import React from "react";
import ReactDOM from 'react-dom';
import PropTypes from "prop-types";
import FormsStatic from "../FormsStatic";

class ThreeStateCheckbox extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: this.props.value || "0",
            checked: false
        }
    }
    componentDidMount() {
        if (this.state.value != "0") {
            this.state.value == "1" ? this.setState({ checked: true }) : ReactDOM.findDOMNode(this).indeterminate = true;
        }
    }

    changeCbState() {
        if (this.state.value == "0") {
            this.state.value = "1";
            this.setState({ checked: true })
            ReactDOM.findDOMNode(this).indeterminate = false;
        }
        else if (this.state.value == "1") {
            this.state.value = "2";
            this.setState({ checked: false })
            ReactDOM.findDOMNode(this).indeterminate = true;
        }
        else {
            this.state.value = "0";
            this.setState({ checked: false })
            ReactDOM.findDOMNode(this).indeterminate = false;
        }
        this.props.onChange(this.state.value);
    }
    render() {
        const uniqueId = FormsStatic.guid();
        return (
            <div className="custom-control custom-checkbox">
                <input
                    type="checkbox"
                    className="custom-control-input"
                    id={"others-" + uniqueId}
                    checked={this.state.checked}
                    onChange={() => {
                        this.changeCbState();
                    }}
                />
                <label className="custom-control-label" htmlFor={"others-" + uniqueId}>
                </label>
            </div>
        );
    }
}

ThreeStateCheckbox.propTypes = {
    className: PropTypes.string,
    value: PropTypes.string,
    onChange: PropTypes.func
}

export default ThreeStateCheckbox;

设置复选框不确定的方法是什么?

编辑:在changeCbState我可以通过 eventargs (ev.target)访问复选框,但我也需要它在componentDidMount(). 仍然不知道如何在那里访问它。

标签: javascriptreactjscheckboxbootstrap-4

解决方案


创建一个ref并使用它来控制 DOM 级别中的不确定性:

constructor(props) {
    //...
    this.checkboxRef = React.createRef();
    //...
}

然后将ref道具添加到您的复选框。

<input
    type="checkbox"
    ...
    ref={this.checkboxRef}
/>

现在您可以使用以下代码来设置不确定状态:

this.checkboxRef.indeterminate = true

推荐阅读