0

这是我的堆栈闪电战:

https://stackblitz.com/edit/svgtest

JSX

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import { observer } from 'mobx-react';
import { observable } from 'mobx';
import { MountingViewModel } from './MountingViewModel';
import { Roof } from './roof';
import { Facade } from './facade';

interface AppProps { }
interface AppState {
  name: string;
}

@observer
class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React'
    };
  }

  onClick = (e) => {
    alert(e.currentTarget.id);
    // set opcacity to 0.5 to all others id`s
  }

  @observable mountings: Set<MountingViewModel> = new Set();

  roofViewModel: MountingViewModel = new MountingViewModel(false, "roof");
  facadeViewModel: MountingViewModel = new MountingViewModel(false, "facade");

  componentDidMount() {
    this.mountings.add(this.roofViewModel);
    this.mountings.add(this.facadeViewModel);
  }

  renderSvg() {
    return <svg height="400" width="400" xmlns="http://www.w3.org/2000/svg">
      {  
        this.mountings.has(this.roofViewModel) && <Roof id={"roof"} />
      }
      {
        this.mountings.has(this.facadeViewModel) && <Facade id={"facade"} />
      }

    </svg>
  }

  onMouseOver = (e) => {
    let data = e.currentTarget;
    alert(data.style);
  }

  render() {
    return this.renderSvg()

  }
}

render(<App />, document.getElementById('root'));

屋顶和立面组件没有渲染,因为 Set.has 方法没有返回 true,尽管我会说对象相等!

为什么这两个组件没有渲染?

4

1 回答 1

0

MobX 还不支持 observable Sets。相反,您可以将您的视图保存在一个可观察的数组中,并且您的组件将在数组更改时重新渲染。

@observer
class App extends Component<AppProps, AppState> {
  // ...

  @observable mountings: MountingViewModel[] = [];

  componentDidMount() {
    this.mountings.push(this.roofViewModel);
    this.mountings.push(this.facadeViewModel);
  }

  renderSvg() {
    return <svg height="400"   width="400" xmlns="http://www.w3.org/2000/svg">
      {  
        this.mountings.indexOf(this.roofViewModel) === -1 && <Roof id={"roof"} isSelected={this.roofViewModel.isSelected}  />
      }
      {
        this.mountings.indexOf(this.facadeViewModel) === -1 && <Facade id={"facade"} isSelected={this.facadeViewModel.isSelected} />
      }
    </svg>
  }

  render() {
    return this.renderSvg()
  }
}
于 2018-07-10T20:22:53.280 回答