optionsLineComponent.tsx 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import * as React from "react";
  2. import { Observable } from "babylonjs/Misc/observable";
  3. import { PropertyChangedEvent } from "./propertyChangedEvent";
  4. class ListLineOption {
  5. public label: string;
  6. public value: number;
  7. }
  8. interface IOptionsLineComponentProps {
  9. label: string,
  10. target: any,
  11. propertyName: string,
  12. options: ListLineOption[],
  13. noDirectUpdate?: boolean,
  14. onSelect?: (value: number) => void,
  15. onPropertyChangedObservable?: Observable<PropertyChangedEvent>
  16. }
  17. export class OptionsLineComponent extends React.Component<IOptionsLineComponentProps, { value: number }> {
  18. private _localChange = false;
  19. constructor(props: IOptionsLineComponentProps) {
  20. super(props);
  21. this.state = { value: props.target[props.propertyName] };
  22. }
  23. shouldComponentUpdate(nextProps: IOptionsLineComponentProps, nextState: { value: number }) {
  24. if (this._localChange) {
  25. this._localChange = false;
  26. return true;
  27. }
  28. const newValue = nextProps.target[nextProps.propertyName];
  29. if (newValue != null && newValue !== nextState.value) {
  30. nextState.value = newValue;
  31. return true;
  32. }
  33. return false;
  34. }
  35. raiseOnPropertyChanged(newValue: number, previousValue: number) {
  36. if (!this.props.onPropertyChangedObservable) {
  37. return;
  38. }
  39. this.props.onPropertyChangedObservable.notifyObservers({
  40. object: this.props.target,
  41. property: this.props.propertyName,
  42. value: newValue,
  43. initialValue: previousValue
  44. });
  45. }
  46. updateValue(valueString: string) {
  47. const value = parseInt(valueString);
  48. this._localChange = true;
  49. const store = this.state.value;
  50. if (!this.props.noDirectUpdate) {
  51. this.props.target[this.props.propertyName] = value;
  52. }
  53. this.setState({ value: value });
  54. this.raiseOnPropertyChanged(value, store);
  55. if (this.props.onSelect) {
  56. this.props.onSelect(value);
  57. }
  58. }
  59. render() {
  60. return (
  61. <div className="listLine">
  62. <div className="label">
  63. {this.props.label}
  64. </div>
  65. <div className="options">
  66. <select onChange={evt => this.updateValue(evt.target.value)} value={this.state.value}>
  67. {
  68. this.props.options.map(option => {
  69. return (
  70. <option key={option.label} value={option.value}>{option.label}</option>
  71. )
  72. })
  73. }
  74. </select>
  75. </div>
  76. </div>
  77. );
  78. }
  79. }