1.效果预览
2.第三方库安装
npm i axios //安装axios库
获取bootstrap.css(找到链接ctrl+s保存网页即可):https://www.bootcdn.cn/twitter-bootstrap/
存放路径:/public/css/bootstrap.css
3.具体代码
/public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="stylesheet" href="./css/bootstrap.css">
<title></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
/src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App' //引入App组件
//渲染App到页面
ReactDOM.render(<App/>,document.getElementById('root'));
/src/App.js
import React,{Component} from 'react'
import Search from './components/Search'
import List from './components/List'
export default class App extends Component{
state = {
users:[], //存放用户数据
isFirst:true, //是否为第一次打开页面
isLoading:false, //标识是否处于加载中
err:'' //存储请求相关的错误信息
}
//更新App的state
updateAppState = (stateObj)=>{
this.setState(stateObj)
}
render(){
return (
<div className="container">
<Search updateAppState={this.updateAppState}/>
<List {...this.state}/>
</div>
)
}
}
/src/components/Search/index.jsx
import React, { Component } from 'react'
import axios from 'axios'
export default class Search extends Component {
search = ()=>{
const {keyWordElement:{value:keyWord}} = this //获取用户的输入内容
//发送请求前更新APP状态
this.props.updateAppState({isFirst:false,isLoading:true})
//发送网络请求
axios.get(`http://api.github.com/search/users?q=${keyWord}`).then(
response => {
//请求成功后更新APP状态
this.props.updateAppState({isLoading:false,users:response.data.items})
},
error => {
//请求失败后更新APP状态
this.props.updateAppState({isLoading:false,err:error.message})
}
)
}
render() {
return (
<section className="jumbotron">
<h3 className="jumbotron-heading">Search Github Users</h3>
<div>
<input ref={c => this.keyWordElement = c} type="text" placeholder="enter the name you search"/>
<button onClick={this.search}>Search</button>
</div>
</section>
)
}
}
/src/components/List/index.jsx
import React, { Component } from 'react'
import './index.css'
export default class List extends Component {
render() {
const {users,isFirst,isLoading,err} = this.props
return (
<div className="row">
{
isFirst ? <h2>Welcome!</h2> :
isLoading ? <h2>Loading...</h2> :
err ? <h2 style={{color:'red'}}>{err}</h2> :
users.map((userObj)=>{
return (
<div key={userObj.id} className="card">
<a rel="noreferrer" href={userObj.html_url} target="_blank">
<img alt="profile_picture" src={userObj.avatar_url} style={{width: '100px'}}/>
</a>
<p className="card-text">{userObj.login}</p>
</div>
)
})
}
</div>
)
}
}
/src/components/List/index.css
.album {
min-height: 50rem; /* Can be removed; just added for demo purposes */
padding-top: 3rem;
padding-bottom: 3rem;
background-color: #f7f7f7;
}
.card {
float: left;
width: 33.333%;
padding: .75rem;
margin-bottom: 2rem;
border: 1px solid #efefef;
text-align: center;
}
.card > img {
margin-bottom: .75rem;
border-radius: 100px;
}
.card-text {
font-size: 85%;
}