用户搜索练习:
步骤:
1.首先,建立app.jsx、main.jsx、search.jsx三个文件,(这里是我将分为app上显示搜索框,和将要搜索内容)
2.先在app.jsx中:
import React, { Component } from 'react'
import Search from './search'
import Main from './mian'
export default class App extends Component{
//2.初始化需要搜索内容
state ={
searchName: ""
}
//3.书写search.jsx中所需要的方法
setSearchName = (searchName) =>{
//更新数据
this.setState({searchName})
}
render() {
return(
//1.先写好主体内容
<div className="container">
<Search setSearchName={this.setSearchName}/>
<Main searchName={this.state.searchName}/>
</div>
)
}
}
在search.jsx中添加
import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class Search extends Component{
//7.父组件传过来的方法函数
static propTypes={
setSearchName:PropTypes.func.isRequired
}
//6.书写点击事件方法
search= () => {
//得到输入的关键字
const searchName= this.input.value.trim()
if(searchName){
//8.搜索
this.props.setSearchName(searchName)
}
}
render(){
return(
//4.先写静态显示页面
<section className="jumbotron">
<h3 className="jumbotron-heading">Search Github Users</h3>
<div>
//6.添加非受控组件,将input值传入父组件
<input type="text" placeholder="enter the name you search" ref={input => this.input=input}/>
//5.添加点击事件
<button onClick={this.search}>Search</button>
</div>
</section>
)
}
}
最后main
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'
export default class Main extends Component{
//9.父组件传入的
static propTypes ={
searchName:PropTypes.string.isRequired
}
// 10.书写初始化
state={
initView: true,
loading:false,
users:null,
errorMsg:null
}
//12.当组件接收到新的属性时回调
componentWillReceiveProps(newProps){
const{searchName}=newProps
//更新状态(请求中)
this.setState({
initView: false,
loading: true
})
//ajax发请求
const url =`https://api.github.com/search/users?q=${searchName}`
axios.get(url)
.then(response => {
//得到响应数据
const result = response.data
console.log(result)
const users =result.items.map(item =>
({ name: item.login, url: item.html_url, avatarUrl: item.avatar_url}
))
this.setState({loading: false, users})
})
.catch(error =>{
//更新状态(失败)
this.setState({loading: false, errorMsg: error.message})
})
}
render(){
// 11.书写静态页面
const { initView, loading, users, errorMsg } =this.state
const { searchName } =this.props
if(initView){
return<h2>请输入关键字{searchName}</h2>
}else if(loading){
return<h2>正在请求中......</h2>
}else if(errorMsg){
return<h2>{errorMsg}</h2>
}else{
return(
<div className="row">
<div>
{ users.map((user, index) => (
<div className="card" key={index}>
<a href={users.url} target="_blank">
<img src={ users.avatarUrl } style={{width: 100 }}/>
</a>
<p className="card-text">{ user.name }</p>
</div>
)) }
</div>
</div>
)
}
}
}