上一節說到使用react完成布局和html代碼的展示。這一章節將講解react的數據的綁定。
一、需要使用的React api
1、getInitialState方法,在ES5的語法中用來設置組件的初始化的數據。在該方法中定義要使用的數據模型。
??2、setState方法,用來更新組件的數據并更新視圖
??3、forceUpdate方法,強制更新數據和視圖
??4、refs屬性用來從組件的dom中獲取到實際的ref指定的dom元素
??5、this.state.xxxx能夠獲取當前組件中在getInitialState中的數據模型的值
??6、this.props.xxxx能夠從父組件獲取傳遞過來的值
上一節中,定義了兩個組件,展示列表組件和編輯列表組件。現完成兩個組件的數據的綁定。
分析:1、展示列表組件,該組件具有刪除和編輯的功能,需要添加兩個事件,remove和edit。
???2、編輯列表組件,該組件提供編輯輸入,保存編輯,刪除功能,數據由父組件提供。
???3、父組件List提供子組件的數據和子組件方法的具體實現。
具體代碼如下:
單獨的/**
* Created by Lenovo on 2017/4/7.
*/
//展示組件
const Item = React.createClass({
//刪除方法
remove(){
this.props.onRemove(this.props.id);
},
//編輯方法
edit(){
this.props.onEdit(this.props.id,this.props.value);
},
render(){
return <li className="list-group-item">
{this.props.value}//此處為通過props來接受從父組件傳遞過來的數據并綁定到虛擬的dom上
<a href="#" className="item-right glyphicon glyphicon-remove" onClick={this.remove}></a>
<a href="#" className="item-right glyphicon glyphicon-edit" onClick={this.edit}></a>
</li>
}
});
//編輯組件
const EditItem = React.createClass({
getInitialState(){
return{
value:''
}
},
//將錄入的數據存入到當前的組件的狀態中
changeHandle(event){
this.setState({value:event.target.value});
},
//保存方法調用父組件中的保存方法
save(){
this.props.onSave(this.props.id,this.state.value);
},
//刪除方法調用父組件中的刪除方法
remove(){
this.props.onRemove(this.props.id);
},
render(){
return <li className="list-group-item">
<input type="text" onChange={this.changeHandle} defaultValue={this.props.value}/>
<a href="#" className="margin-leftandright-5 glyphicon glyphicon-share" onClick={this.save}></a>
<a href="#" className="margin-leftandright-5 glyphicon glyphicon-remove" onClick={this.remove}></a>
</li>
}
});
//容器組件
const List = React.createClass({
getInitialState(){
return{
key:0,
List:new Map(),
eList:new Map()
}
},
//添加方法的具體實現
add(){
const key=this.state.key++;
this.state.eList.set(key,'');
this.forceUpdate();
},
//保存方法的具體實現
save(id,value){
this.state.List.set(id,value);
this.state.eList.delete(id);
this.forceUpdate();
},
//展示列表刪除方法的具體實現
remove(id){
this.state.List.delete(id);
this.forceUpdate();
},
//編輯列表刪除方法的具體實現
eremove(id){
this.state.eList.delete(id);
this.forceUpdate();
},
//展示列表編輯方法的具體實現
edit(id,value){
this.state.eList.set(id,value);
this.state.List.delete(id);
this.forceUpdate();
},
render(){
const ListDom=[];
const EditListDom=[];
for(let entity of this.state.List){
ListDom.push(<Item value={entity[1]} id={entity[0]}
onRemove={this.remove}
onEdit={this.edit}
/>)
}
for(let entity of this.state.eList){
EditListDom.push(<EditItem value={entity[1]}
id={entity[0]}
onSave={this.save}
onRemove={this.eremove}
/>)
}
return <div>
<button className="menu-btn btn btn-success glyphicon glyphicon-plus" onClick={this.add}>
添加心事
</button>
<ul className="list-group">
{ListDom}
{EditListDom}
</ul>
</div>
}
});
//渲染
ReactDOM.render(
<List/>,
document.getElementById('content')
);
本節講了數據和dom元素綁定,該項目還存在很多的不好的交互行為,需要進行優化,下一節將對該項目進行優化。