checkBoxLineComponent.tsx 2.8 KB

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