【发布时间】:2019-01-21 05:08:06
【问题描述】:
我已经制作了这个应该是“三态复选框”的复选框,它不仅将不确定状态用作“视觉值”,还用作“真实”值。如果我只使用标准复选框,它可以正常工作,但如果我使用引导自定义复选框,它就不再起作用了,因为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;
checkbox不定的设置方法是什么?
编辑:在changeCbState 中,我可以通过 eventargs (ev.target) 访问复选框,但我在componentDidMount() 中也需要它。仍然不知道如何在那里访问它。
【问题讨论】:
标签: javascript reactjs checkbox bootstrap-4