1、List组件
index.js
javascript
import React, {Component} from "react";
//引入样式
import "./index.css";
export default class List extends Component {
render() {
const {users,isFirst,isLoding,err}=this.props
return(
<div className="row">
{
isFirst?<h2>欢迎使用,输入关键字,随后点击搜素</h2>:
isLoding?<h2>正在加载中...</h2>:
err?<h2 style={{color:'red'}}>{err}</h2>:
users.map((userObj)=>{
return(
<div key={userObj.id} className="card">
<a href={userObj.html_url} target="_blank" rel="noreferrer">
<img alt={"reactjs"} src={userObj.avatar_url} style={{width: '100px'}}/>
</a>
<p className="card-text">{userObj.login}</p>
</div>
)
})
}
</div>
);
}
}
index.css
javascript
.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%;
}
2、search组件
javascript
import React, {Component} from "react";
//引入axios
import axios from 'axios';
export default class Search extends Component {
search = () =>{
//获取用户的输入(连续解构赋值+重命名)
const {keyword:{value:keyword}} = this;
//发送请求前通知App组件更新状态
this.props.updateAppState({isFirst:false,isLoding: true});
//发送网络请求 https://api.github.com/search/users?q=xxxxxx
axios.get(`https://api.github.com/search/users?q=${keyword}`).then(
res=>{
const {items} = res.data;
this.props.updateAppState({isLoding:false,users:items});
console.log(items)
},
err=>{
//请求失败通知App组件更新状态
this.props.updateAppState({isLoding:false,err:err.message});
}
)
}
render()
{
return(
<section className="jumbotron">
<h3 className="jumbotron-heading">Search Github Users</h3>
<div>
<input ref={c=>this.keyword=c} type="text" placeholder="enter the name you search"/>
<button onClick={this.search}>Search</button>
</div>
</section>
);
}
}
3、App.js
javascript
//创建"外壳"组件APP
import React, {Component} from "react";
//引入Search组件
import Search from "./components/Search";
//引入List组件
import List from "./components/List";
//创建并暴露App组件
export default class App extends Component {
state={
users:[],
isFirst:true,//是否第一次加载数据
isLoding:false,//是否正在加载数据
err:''//是否加载失败
}
updateAppState=(stateObj)=>{
this.setState({...stateObj})
}
render() {
return (
<div className="container">
<Search updateAppState={this.updateAppState}></Search>
<List {...this.state}></List>
</div>
)
}
}
5、index,js
javascript
//引入React核心库
import React from 'react';
//引入ReactDOM
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
// <React.StrictMode>作用:在开发模式下,React 会在渲染组件时检查其代码,以发现一些常见错误。
<React.StrictMode>
<App />
</React.StrictMode>
);