寫在前面,使用ES6語法
1. 程序結(jié)構(gòu)
- app/
- index.jsx (程序入口)
- components/ (組件文件夾)
- plist.jsx (展示用戶列表)
- search.jsx (搜索框組件)
- utils/ (工具類)
- templates (模版文件夾)
- index.html
- mobile.html
- package.json (項(xiàng)目及npm包版本信息)
- webpack.config.js (webpack配置文件)
2. 完善程序內(nèi)容
根據(jù)上面的圖 把項(xiàng)目分為兩個(gè)主要的component,一個(gè)是Search Box用來讓用戶填寫用戶名, 一個(gè)是List,用來展示搜索到用戶的列表。
2.1 寫入search.jsx文件
Search Box非常的簡單 就是兩個(gè)input,當(dāng)用戶點(diǎn)擊Search的時(shí)候,把輸入的名字發(fā)送到List的組件里面。
import React from 'react';
import ReactDOM from 'react-dom';
export default class Search extends React.Component {
constructor(props) {
super(props);
this.handleSearch = this.handleSearch.bind(this);
}
handleSearch() {
let name = ReactDOM.findDOMNode(this.refs.name).value;
if (name === '') {
return;
}
this.props.sendAction(name);
}
render() {
return (
<div>
<input type="text" ref="name" placeholder="輸入你想搜索的關(guān)鍵詞"/>
<button onClick={this.handleSearch}>Search</button>
</div>
)
}
}
2.2 寫入list.jsx文件
List的目標(biāo)是接受props傳進(jìn)來的name參數(shù),發(fā)起一個(gè)ajax請求,然后用返回值更新整個(gè)列表,這個(gè)列表有幾種狀態(tài) 初始狀態(tài),第一次渲染返回一行提示文字。 Loading的狀態(tài),當(dāng)有props傳進(jìn)來的時(shí)候,發(fā)起ajax請求,并且顯示一個(gè)loading的提示。 完成狀態(tài),當(dāng)請求完畢,渲染列表并且顯示出來。