在项目中,我在下面的代码中使用ui组件以伪时钟的形式表示。
如何使代码工作而不改变实际上是外部库的代码时钟。
最重要的是这个决定是出于mobx的精神。
class ClockStore {
@observable data = [
{id: "hour", value: "00"},
{id: "min", value: "00"},
{id: "second", value: "00"},
];
@action
update(id, value){
this.data.find(item => item.id === id).value = value;
}
}
let clockStore = new ClockStore();
@inject('clockStore')
@observer
class App extends Component<any, any> {
render(){
return <Clock data={this.props.clockStore.data}></Clock>
}
}
// it's not my clock this component is taken from github
class Clock extends Component<any, any> {
render(){
return (
<div>
<ClockFace data={this.props.data} />
<div className="clock-control"></div>
</div>
)
}
}
class ClockFace extends Component<any, any> {
render(){
return (
<div className="clock-face">
{this.props.data.map( ( item, index ) => <ClockSection key={ index }>{ item.value }</ClockSection> )}
</div>
)
}
}
class ClockSection extends Component<any, any> {
render(){
return (
<span className="clock-section">{ this.props.children }</span>
)
}
}
let stores = { clockStore };
ReactDOM.render(
<Provider {...stores}>
<App />
</Provider>,
document.querySelector( 'main' )
);
// the code that sets the clock
let count = 0;
document.addEventListener( 'click', () => clockStore.update( 'hour', count ++ ) );
// --------------------------
答案 0 :(得分:1)
@inject('clockStore')
@observer
class App extends Component<any, any> {
render(){
return <Clock data={ mobx.toJS( this.props.clockStore.data } }></Clock>
}
}
或
class ClockStore {
@observable data = [
{id: "hour", value: "00"},
{id: "min", value: "00"},
{id: "second", value: "00"},
];
getData(){
return toJS( this.data );
}
@action
update(id, value){
this.data.find(item => item.id === id).value = value;
}
}
@inject('clockStore')
@observer
class App extends Component<any, any> {
render(){
console.log( 'app' );
return <Clock data={this.props.clockStore.getData()}></Clock>
}
}