import React from 'react'
import { render } from 'react-dom'
import { observable, computed } from 'mobx'
import { observer } from 'mobx-react'
class Todo {
id = Math.random()
@observable title
@observable finished = false
constructor(title) {
this.title = title
}
}
class TodoList {
@observable todos = []
@computed get unfinishedTodoCount() {
return this.todos.filter(todo => !todo.finished).length
}
}
const TodoView = props => {
return (
<li>
<input type="checkbox" checked={props.todo.finished} onClick={() => {props.todo.finished = !props.todo.finished}}/>{props.todo.title}
</li>
)
}
const TodoListView = observer(props => {
return (
<div>
<ul>
{
props.todoList.todos.map(todo => <TodoView key={todo.id} todo={todo}></TodoView>)
}
</ul>
Task left: {props.todoList.unfinishedTodoCount}
</div>
)
})
const store = new TodoList()
store.todos.push(
new Todo("Get Coffee"),
new Todo("Write simpler code")
)
const App = props => {
return (
<TodoListView todoList={store}/>
)
}
render(<App store={store}/>, document.getElementById('app'))
以上有几点需要注意:
- @observer只能用在类组件前面,在函数组件前使用会报
Leading decorators must be attached to a class declaration
- 装饰器语法处于实验室语法,目前浏览器还不支持,当在项目中使用时会报
对修饰器的实验支持是一项将在将来版本中更改的功能。设置 "experimentalDecorators" 选项以删除此警告。
在项目->首选项->设置中搜索experimentalDecorators,关闭对修饰器校验。
上面处理仅仅使vscode支持修饰器语法,但打包时babel并不支持,会报Support for the experimental syntax 'decorators-legacy' isn't currently enabled
。我们需要安装@babel/plugin-proposal-decorators
,然后在plugins
中加上["@babel/plugin-proposal-decorators", { "legacy": true }]
- 在打包时还会报
Support for the experimental syntax 'classProperties' isn't currently enabled
,这是因为babel不支持类属性语法,因此需要安装@babel/plugin-proposal-class-properties
并在plugins
中配置["@babel/plugin-proposal-class-properties", { "loose": true }]
整个.babelrc
配置如下:
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": [
"@babel/plugin-transform-runtime",
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties", { "loose": true }]
]
}
打包后运行结果:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。