1. 前言
1.antd-mobile
2.這里使用antd的移動(dòng)端框架antd-mobile來分析下react中的輸入框具體用法
2. render
2.1 按需引入需要的組件
import { List, InputItem, Button, WingBlank, WhiteSpace } from 'antd-mobile'
2.2 分析
1.List 簡(jiǎn)單說就是白底的容器
2.InputItem 輸入框
3.Button 按鈕
4.WingBlank 2翼留白 雙標(biāo)簽
5.WhiteSpace 上下留白 單標(biāo)簽
2.3 render代碼
<div>
<List >
<WingBlank>
<InputItem placeholder="請(qǐng)輸入"
labelNumber={20}
value={searchValue}
onChange={this.onChange}
clear
/>
<WhiteSpace />
<Button type="primary" size="small"
disabled={isDisabled}
onClick={() => {
this.searchSub()
}}>提交</Button></WingBlank>
<WhiteSpace />
</List>
</div>
2.4分析 InputItem
1.clear 輸入框后邊會(huì)有個(gè)
x清空按鈕
2.labelNumber 標(biāo)簽的文字個(gè)數(shù)
3.onChange change 事件觸發(fā)的回調(diào)函
3. onChange 事件
1.react沒有
vue的v-model
2.需要在change事件獲取用戶輸入的值,事件參數(shù)就是用戶輸入的值
3.界面需要更改 必須通過setState()函數(shù)來修改
4.react就是實(shí)現(xiàn)了 類似vue的雙向綁定
// 搜索框change事件
// react 沒有 v-model
onChange = (value) => {
// console.log("輸入內(nèi)容:", value)
this.setState({
searchValue: value,
})
if (value.length < 1) {
// 為空 提交按鈕 不可點(diǎn)擊
this.setState({
isDisabled: true,
hasError: true,
})
Toast.info("不能為空")
} else {
this.setState({
isDisabled: false,
hasError: false,
})
}
}
5.
state可以寫到構(gòu)造函數(shù)constructor外部,但是名字必須是state
state = {
searchValue: "",
listData: [],
isDisabled: true,
hasError: false
}
4. 請(qǐng)求需要獲取 輸入框的值
4.1 核心代碼
// 搜索請(qǐng)求
async searchRequest() {
let { cityId } = this.props.match.params
let { searchValue } = this.state
let params = {
city_id: cityId,
keyword: searchValue
}
// async await
// await 必須放在 async 里面使用
try {
let searchResult = await axios.get("/test/user", { params })
return searchResult
} catch (error) {
console.log("搜索錯(cuò)誤信息:", error)
}
}
4.2 分析
1.
cityId是通過路由跳轉(zhuǎn) 動(dòng)態(tài)綁定的參數(shù)
2.searchValue就是解構(gòu)出來的輸入框的值
3.awaitt規(guī)定必須放在async的函數(shù)中
4.async用來搞異步函數(shù)
5.其實(shí)這個(gè)await在Promise中就簡(jiǎn)單理解為脫掉一層then的殼就行
5. 提交事件
- 按鈕點(diǎn)擊的提交事件
5.1 核心代碼
//**** 提交事件
async searchSub() {
let result = (await this.searchRequest()).data
// this.state.listData = result 錯(cuò)誤的寫法 XXX
this.setState({
listData: result,
// 提交完 輸入框清空
searchValue: "",
isDisabled: true
})
}
5.2 分析
1.
async/await語法
2.setState修改函數(shù)