準備工作
安裝nodejs和npm,設置淘寶鏡像等,自行百度。
使用react腳手架來搭建應用
npx craet-react-app appName
執行完得到以下目錄結構:
在安裝目錄下執行npm start
,會在瀏覽器打開localhost:3000:
開始編寫
先在src下新建一個TodoItem文件:
import React,{Component} from 'react';
class TodoItem extends Component{
clickHandle(){
this.props.clickHandle(this.props.index);
}
render(){
return (
<li onClick={this.clickHandle.bind(this)}>{this.props.item}</li>
);
}
}
export default TodoItem;
再新建一個TodoList.js文件。
import React,{Component} from 'react';
import TodoItem from './TodoItem';
class TodoList extends Component{
constructor(){
super();
this.state = {
item:['學習react','學習nodejs','學習ES6'],
input:''
}
}
btnClickHandle(){
this.setState({
item:[...this.state.item,this.state.input],
input:''
})
}
delItem(index){
var list = [...this.state.item];
list.splice(index,1);
this.setState({
item:list
})
}
render(){
return (
<div>
<input value={this.state.input} onChange={(e)=>{this.setState({input:e.target.value})}}/>
<button onClick={()=>{this.btnClickHandle()}}>add</button>
<ul>
{
this.state.item.map((value,index)=>{
return (<TodoItem index={index} key={index} item={value} clickHandle={(i)=>{this.delItem(i)}}/>);
})
}
</ul>
</div>
);
}
}
export default TodoList;
修改index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';
ReactDOM.render(<TodoList />, document.getElementById('root'));
項目完成,運行npm start
,就可以在瀏覽器體驗一個TodoList基本功能了。
總結
1、大愛箭頭函數。不需要在爲函數綁定this,因爲它的this是在定義時確定的,不像普通函數一樣,由調用時決定。
2、JSX語法中,HTML標籤嵌套的大括號相當一個JS代碼的執行環境,裏面可以放JS表達式,但不能寫語句,如if else等
3、React更新頁面不操作DOM節點,而是依靠數據驅動