checkBoxLineComponent.tsx 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import * as React from "react";
  2. import { Observable } from "babylonjs/Misc/observable";
  3. import { PropertyChangedEvent } from "./propertyChangedEvent";
  4. export interface ICheckBoxLineComponentProps {
  5. label: string;
  6. target?: any;
  7. propertyName?: string;
  8. isSelected?: () => boolean;
  9. onSelect?: (value: boolean) => void;
  10. onValueChanged?: () => void;
  11. onPropertyChangedObservable?: Observable<PropertyChangedEvent>;
  12. }
  13. export class CheckBoxLineComponent extends React.Component<ICheckBoxLineComponentProps, { isSelected: boolean }> {
  14. private static _UniqueIdSeed = 0;
  15. private _uniqueId: number;
  16. private _localChange = false;
  17. constructor(props: ICheckBoxLineComponentProps) {
  18. super(props);
  19. this._uniqueId = CheckBoxLineComponent._UniqueIdSeed++;
  20. if (this.props.isSelected) {
  21. this.state = { isSelected: this.props.isSelected() };
  22. } else {
  23. this.state = { isSelected: this.props.target[this.props.propertyName!] === true };
  24. }
  25. }
  26. shouldComponentUpdate(nextProps: ICheckBoxLineComponentProps, nextState: { isSelected: boolean }) {
  27. var currentState: boolean;
  28. if (nextProps.isSelected) {
  29. currentState = nextProps.isSelected!();
  30. } else {
  31. currentState = nextProps.target[nextProps.propertyName!] === true;
  32. }
  33. if (currentState !== nextState.isSelected || this._localChange) {
  34. nextState.isSelected = currentState;
  35. this._localChange = false;
  36. return true;
  37. }
  38. return nextProps.label !== this.props.label;
  39. }
  40. onChange() {
  41. this._localChange = true;
  42. if (this.props.onSelect) {
  43. this.props.onSelect(!this.state.isSelected);
  44. } else {
  45. if (this.props.onPropertyChangedObservable) {
  46. this.props.onPropertyChangedObservable.notifyObservers({
  47. object: this.props.target,
  48. property: this.props.propertyName!,
  49. value: !this.state.isSelected,
  50. initialValue: this.state.isSelected
  51. });
  52. }
  53. this.props.target[this.props.propertyName!] = !this.state.isSelected;
  54. }
  55. if (this.props.onValueChanged) {
  56. this.props.onValueChanged();
  57. }
  58. this.setState({ isSelected: !this.state.isSelected });
  59. }
  60. render() {
  61. return (
  62. <div className="checkBoxLine">
  63. <div className="label">
  64. {this.props.label}
  65. </div>
  66. <div className="checkBox">
  67. <input type="checkbox" id={"checkbox" + this._uniqueId} className="cbx hidden" checked={this.state.isSelected} onChange={() => this.onChange()} />
  68. <label htmlFor={"checkbox" + this._uniqueId} className="lbl"></label>
  69. </div>
  70. </div>
  71. );
  72. }
  73. }