目錄結構:php
Model/index.jscss
'use strict'; import { action, autorun, observable, computed } from "mobx"; export default class TodoList { @observable todos = [{ title: "test", finished: true }]; @observable data = [];
constructor(){
autorun(()=>{console.log(this.unfinishedTodoCount)});
} @computed get unfinishedTodoCount() { return this.todos.filter(todo => !todo.finished).length; } @action getData() { fetch("http://localhost/Server/index.php").then(res => res.json()).then(data => this.data = data); } @action addList() { this.todos.push({ title: "test1", finished: false }); } }
View/index.jshtml
import React,{Component} from "react"; import ReactDOM from "react-dom"; import {observer} from "mobx-react"; import TodoList from "../Model/index"; @observer class TodoListView extends Component { componentDidMount(){ this.props.todoList.getData(); } clickHandle(){ this.props.todoList.addList(); } render() { return <div> <ul> {this.props.todoList.todos.map(todo => <TodoView todo={todo} key={todo.id} /> )} </ul> Tasks left: {this.props.todoList.unfinishedTodoCount}<br /> 姓名:{this.props.todoList.data.name}<br /> 年齡:{this.props.todoList.data.age}<br /> 密碼:{this.props.todoList.data.pass}<br /> <input name='name' type='button' value="按鈕" onClick={this.clickHandle.bind(this)} /> </div> } } const TodoView = observer(({todo}) => <li> <input type="checkbox" checked={todo.finished} onClick={() => {return todo.finished = !todo.finished}} />{todo.title} </li> ) const store = new TodoList(); ReactDOM.render(<TodoListView todoList={store} />, document.getElementById('container'));
webpack.config.jsreact
var webpack = require('webpack'); var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js'); module.exports = { //插件項 // plugins: [commonsPlugin], //頁面入口文件配置 entry: { index: './View/index.js' }, //入口文件輸出配置 output: { path: 'dist/page', filename: '[name].js' }, module: { //加載器配置 loaders: [ { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.js$/, loader: 'babel-loader' }, { test: /\.(png|jpg)$/, loader: 'url-loader' } ] }, };
.babelrcwebpack
{
"presets": ["react", "es2015", "stage-2"],
"plugins": [
"transform-decorators-legacy"
]
}
Page/index.htmles6
<html> <head> <meta charset="utf-8" /> </head> <body> <div id="container"></div> <script src="../dist/page/index.js"></script> </body> </html>