使用腳手架建立 React 專案(二)
阿新 • • 發佈:2019-01-23
在使用腳手架建立 React 專案(一)的基礎上,繼續進行專案的修改。目標:建立簡單的todo元件,只為了簡單的新增功能
1 npm run eject //將專案的配置資訊從預設的依賴包中提取出來,會生成config資料夾
2 使用編輯器,此處使用HbuilderX。(westorm sublime等任意一款編輯器)
3 建立簡單的元件(此處刪除了預設生成的無用檔案),最終如下
src/index.js
import React from 'react'; import ReactDOM,{render} from 'react-dom'; import App from './components/App';//此處使用簡寫方式,App表示的是App資料夾,會預設載入index.js檔案;也可以寫成import App from './components/App/index';注意,非index.js不可省略 render(<App />, document.getElementById('root'));
App/index.js
import React, { Component } from 'react'; import Add from '../Add'; import List from '../List'; class App extends Component { constructor(props){ super(props); this.state = { todoList : [ {todo:'name1',commont:'todo1'}, {todo:'name2',commont:'todo2'} ] }; } Add = (todo)=>{ let {todoList} = this.state;//解構賦值 todoList.unshift(todo);//集合的首位新增 this.setState({todoList});//同名變數名和值的簡寫方式 }; render() { let {todoList} = this.state; return ( <div className="App"> <header className="App-header"> <h1 className="App-title">to do list</h1> </header> <Add Add={this.Add}/> <hr/> <List todolist={todoList}/> </div> ); } } export default App;
Add/index.js
import React, { Component } from 'react'; class Add extends Component { Add = ()=>{ let todo = this.refs.todo.value; let commont = this.refs.commont.value; if(!todo || !commont){ return; } this.props.Add({todo,commont}); this.refs.todo.value = ''; this.refs.commont.value = ''; }; render() { return ( <div className="App"> name<input ref="todo" /> commont<input ref="commont"/> <button onClick={this.Add}>Add</button> </div> ); } } export default Add;
List/index.js
import React, { Component } from 'react';
class List extends Component {
render() {
let {todolist} = this.props;
let display = todolist.length>0?'none':'block';
return (
<div className="App">
<header style={{display}}>
<h1 className="App-title">empty</h1>
</header>
<ul>
{
todolist.map((item,index)=>{
return (
<li key={index}>
<p>{item.todo} ==== {item.commont}</p>
</li>
)
})
}
</ul>
</div>
);
}
}
export default List;
4 啟動專案 npm start