textInputLineComponent.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import * as React from "react";
  2. import { Observable } from "babylonjs/Misc/observable";
  3. import { PropertyChangedEvent } from "./propertyChangedEvent";
  4. interface ITextInputLineComponentProps {
  5. label: string;
  6. target?: any;
  7. propertyName?: string;
  8. value?: string;
  9. onChange?: (value: string) => void;
  10. onPropertyChangedObservable?: Observable<PropertyChangedEvent>;
  11. }
  12. export class TextInputLineComponent extends React.Component<ITextInputLineComponentProps, { value: string }> {
  13. private _localChange = false;
  14. constructor(props: ITextInputLineComponentProps) {
  15. super(props);
  16. this.state = { value: this.props.value || this.props.target[this.props.propertyName!] || "" }
  17. }
  18. shouldComponentUpdate(nextProps: ITextInputLineComponentProps, nextState: { value: string }) {
  19. if (this._localChange) {
  20. this._localChange = false;
  21. return true;
  22. }
  23. const newValue = nextProps.value || nextProps.target[nextProps.propertyName!];
  24. if (newValue !== nextState.value) {
  25. nextState.value = newValue || "";
  26. return true;
  27. }
  28. return false;
  29. }
  30. raiseOnPropertyChanged(newValue: string, previousValue: string) {
  31. if (this.props.onChange) {
  32. this.props.onChange(newValue);
  33. return;
  34. }
  35. if (!this.props.onPropertyChangedObservable) {
  36. return;
  37. }
  38. this.props.onPropertyChangedObservable.notifyObservers({
  39. object: this.props.target,
  40. property: this.props.propertyName!,
  41. value: newValue,
  42. initialValue: previousValue
  43. });
  44. }
  45. updateValue(value: string) {
  46. this._localChange = true;
  47. const store = this.props.value || this.props.target[this.props.propertyName!];
  48. this.setState({ value: value });
  49. this.raiseOnPropertyChanged(value, store);
  50. if (this.props.propertyName) {
  51. this.props.target[this.props.propertyName] = value;
  52. }
  53. }
  54. render() {
  55. return (
  56. <div className="textInputLine">
  57. <div className="label">
  58. {this.props.label}
  59. </div>
  60. <div className="value">
  61. <input value={this.state.value} onChange={evt => this.updateValue(evt.target.value)} />
  62. </div>
  63. </div>
  64. );
  65. }
  66. }