父元件傳遞函式給子元件
阿新 • • 發佈:2018-12-18
文章參考
問題來源
學習react過程中向把Lits列表中的Item項抽象成一個元件,子元件內部有個SwipeAction元件,它需要接受一個物件,物件中包含一個自定義函式,不是直接通過props傳遞的函式;這就有點暈了,不知道jsx能否找到函式的所屬物件,特此做了相關記錄
案例
父元件
// 通過高階函式返回定義的事件,高階函式獲取變數引數,在返回函式中獲取事件物件
deleteGoodsByIdByPost(goodsId, index){
let that = this;
that.state.goodsList.splice(index, 1);
that.setState ({
goodsList : that.state.goodsList
})
GoodsService.deleteGoodsByIdByPost(goodsId)
.then(function(res){
if(res.data == "sucess"){
Toast.success('刪除成功 !!!', 1);
}
});
}
render () {
// 頂部右側按鈕,實現頁面切換
let typeInBtn = <Link to={ "/goodsManage/goodsDetailsAdd" }>錄入</Link>;
return (
<div>
<div className={'contentStyle'}>
{this.state.goodsList.map((currentObj, index, originArr) => {
let rightSwipeConfigArray = [{
text: '刪除',
onPress: this.deleteGoodsByIdByPost.bind(this,currentObj.goodsId, index),
style: { backgroundColor: '#F4333C', color: 'white' },
}];
let url = "/goodsManage/goodsDetailsUpdate/"+currentObj.goodsId;
return (
<GoodsListItemComp key={index} url={url} goodsObj={currentObj} rightSwipeConfigArray={rightSwipeConfigArray}></GoodsListItemComp>
);
})}
</div>
</div>
);
}
子元件GoodsListItemComp
import BaseComponent from '../core/BaseComponent.js';
import { SwipeAction, Button, Toast } from 'antd-mobile';
import { Link } from 'react-router-dom';
/**
* 商品列表的 Item 項元件
*/
class GoodsListItemComp extends BaseComponent {
// GoodsDetails的建構函式,可以執行初始化的操作
constructor (props) {
super(props);
let that = this;
this.imageStyle = {
width: "90px",
height: "auto",
float: "left"
};
let propsRightSwipeConfigArray = null;
if(props.rightSwipeConfigArray == undefined){
propsRightSwipeConfigArray = [];
}else{
propsRightSwipeConfigArray = props.rightSwipeConfigArray;
}
this.state = {
// 商品物件
goodsObj: props.goodsObj,
url: props.url,
rightSwipeConfigArray : propsRightSwipeConfigArray
};
}
render () {
let {goodsObj, rightSwipeConfigArray, url} = this.state;
return (
<SwipeAction style={{ backgroundColor: 'gray' }}
autoClose
right={rightSwipeConfigArray}
>
<Link to={ url }>
<div style={{"background": "#fff"}} >
<img src='src/assets/yay.jpg' style={this.imageStyle}/>
<div style={{"marginLeft": "100px"}}>
<div style={{"fontSize":"16px","lineHeight":"1.8"}}>{goodsObj.goodsName}-{goodsObj.goodsId}</div>
<div style={{"lineHeight":"1.8"}}>售價:{goodsObj.salePrice} 元</div>
<div style={{"clear": "both"}}></div>
</div>
</div>
</Link>
</SwipeAction>
);
}
}
export default GoodsListItemComp;
SwipeAction 的屬性right 定義的方法,最終還是來自父元件傳遞過來的,方法中的this是指向的父元件