1.頁面大致是這個樣子
2.頁面結構
-
<div className="col-md-10">
-
<select name="" onChange={(e) => this.onFirstCategoryChange(e)} className="form-control cate-select">
-
<option value="">請選擇一級分類</option>
-
{
-
//箭頭函數=>右邊,加上了{}就需要return,不加就不需要return
-
this.state.firstCategoryList.map(
-
(category, index) => <option value={category.id} key={index}>{category.name}</option>)
-
}
-
</select>
-
{ this.state.secondCategoryList.length ?
-
<select name="" onChange={(e) => this.onSecondCategoryChange(e)} className="form-control cate-select">
-
<option value="">請選擇二級分類</option>
-
{
-
this.state.secondCategoryList.map(
-
(category, index)=> <option value={category.id} key={index}>{category.name}</option>
-
)
-
}
-
</select> : null
-
}
-
</div>
3.定義state里邊的數據
-
this.state = {
-
firstCategoryList : [],
-
firstCategoryId : 0,
-
secondCategoryList : [],
-
secondCategoryId : 0,
-
}
監聽select選擇框,當一級品類和二級品類改變的時候, 更新state里邊firstCategoryId和secondCategoryId的值
-
//一級品類改變事件
-
onFirstCategoryChange(e){
-
//取一級品類的值,沒有的話為0
-
let newValue=e.target.value || 0;
-
this.setState({
-
-
firstCategoryId : newValue,
-
//當一級品類改變時清空二級品類
-
secondCategoryList : [],
-
secondCategoryId : 0,
-
},() => {
-
//加載二級分類
-
this.loadSecondCategory()
-
})
-
}
-
//二級品類改變事件
-
onSecondCategoryChange(e){
-
//取一級品類的值,沒有的話為0
-
let newValue=e.target.value || 0;
-
this.setState({
-
secondCategoryId : newValue,
-
},() => {
-
//加載二級分類
-
this.onPropsCategoryChange();
-
})
-
}
加載一級分類
-
//加載一級分類
-
loadFirstCategory(){
-
_product.getCategoryList().then(res => {
-
this.setState({
-
firstCategoryList : res
-
});
-
}, errMsg => {
-
_mm.errorTips(errMsg);
-
});
-
}
加載二級分類
-
//加載二級分類
-
// 加載二級分類
-
loadSecondCategory(){
-
_product.getCategoryList(this.state.firstCategoryId).then(res => {
-
this.setState({
-
secondCategoryList : res
-
});
-
}, errMsg => {
-
_mm.errorTips(errMsg);
-
});
-
}
4.把最新的firstCategoryId和secondCategoryId的值傳入父組件,更新父組件里邊一級品類和二級品類
-
// 傳給父組件選中的結果
-
onPropsCategoryChange(){
-
// 判斷props里的回調函數存在
-
let categoryChangable = typeof this.props.onCategoryChange === 'function';
-
// 如果是有二級品類
-
if(this.state.secondCategoryId){
-
categoryChangable && this.props.onCategoryChange(this.state.secondCategoryId, this.state.firstCategoryId);
-
}
-
// 如果只有一級品類
-
else{
-
categoryChangable && this.props.onCategoryChange(this.state.firstCategoryId, 0);
-
}
-
}
父組件使用CategorySelector組件
-
<div className="form-group">
-
<label className="col-md-2 control-label">所屬分類</label>
-
<CategorySelector
-
categoryId={this.state.categoryId}
-
parentCategoryId={this.state.parentCategoryId}
-
onCategoryChange={ (categoryId,parentCategoryId) => this.onCategoryChange(categoryId,parentCategoryId)} />
更新父組件state里邊一級品類和二級品類的值
-
//品類改變事件
-
onCategoryChange(categoryId,parentCategoryId){
-
this.setState({
-
categoryId : categoryId,
-
parentCategoryId : parentCategoryId
-
});
-
}