javascript - 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()
. 仍然不知道如何在那里访问它。
解决方案
创建一个ref
并使用它来控制 DOM 级别中的不确定性:
constructor(props) {
//...
this.checkboxRef = React.createRef();
//...
}
然后将ref
道具添加到您的复选框。
<input
type="checkbox"
...
ref={this.checkboxRef}
/>
现在您可以使用以下代码来设置不确定状态:
this.checkboxRef.indeterminate = true
推荐阅读
- r - optim() 根据规模陷入局部最小值
- c# - ASP.NET MVC 中的 MultiSelectList 有问题吗?
- python - 使用 Python 的图形工具在 DAG 中实现有效的最短路径
- javascript - 仅当图像已存在时如何删除图像
- c# - 在 Android 应用程序上设置 Twilio 推送通知
- reactjs - react-native-modal 正在调试但未发布
- python - 根据条件查找最后一个元素索引
- geany - 在创建新文件之前在与工作文件相同的文件夹中创建新文件?
- intellij-idea - sbt 执行期间出错:java.util.NoSuchElementException:空流的头
- android - Unity错误显示-没有连接android设备