文章參考
React學習–JSX與react事件
下面我根據使用難易的順序做了下面三個例子
一、使用bind函數獲取event對象
react事件參數的傳遞通過綁定來實現,在傳遞時,綁定的this在前,參數在后,在定義函數時,事件對象e要放在最后
/**
* 刪除列表中選中的行
* @param index 數組的索引
* @param e Event對象,使用bind方式綁定函數,event對象作為最后一個參數注入
*/
deleteCurrentItem(index, e){
// 刪除數組中選中的索引數據
this.state.data.splice(index, 1);
this.setState({
data : that.state.data
})
}
render(){
let that = this;
// 頂部右側按鈕,實現頁面切換
let typeInBtn = <Link to={ "/inWarehouse/inWarehouseInput" }>錄入</Link>
let listContent = this.state.data.map(function(obj, index, currentArray){
return (
<div key={obj} style={{"background": "#fff"}} onClick={that.deleteCurrentItem.bind(that,index)}>
<img src='src/assets/yay.jpg' style={that.imageStyle}/>
<div style={{"marginLeft": "100px"}}>
<div style={{"fontSize":"16px","lineHeight":"1.8"}}>黃瓜薯片----{obj}</div>
<div style={{"lineHeight":"1.8"}}>售價:8 元</div>
<div style={{"clear": "both"}}></div>
</div>
</div>
)
});
return (
<div>{listContent}</div>
)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
二、 箭頭函數獲取event對象
class MyIndex extends BaseComponent {
testEvent(params,eventObj){
console.log(params);
console.dir(eventObj);
}
render () {
return (
<div>
<Button onClick={(e)=>this.testEvent("params",e)}>綁定事件測試</Button>
</div>
);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
三、使用高階函數獲取event對象
// 通過高階函數返回定義的事件,高階函數獲取變量參數,在返回函數中獲取事件對象
jsxDeleteGoodsByIdByPost(goodsId, index){
let that = this;
// eventObj是Event對象,在JSX中
return function(eventObj){
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);
}
});
}
}
<SwipeAction key={currentObj + index}
style={{ backgroundColor: 'gray' }}
autoClose
right={[
{
text: '刪除',
onPress: this.jsxDeleteGoodsByIdByPost(currentObj.goodsId, index),
style: { backgroundColor: '#F4333C', color: 'white' },
}
]}
>
<Link to={"/goodsManage/goodsDetailsUpdate/"+currentObj.goodsId}>
<div style={{"background": "#fff"}} >
<img src='src/assets/yay.jpg' style={this.imageStyle}/>
<div style={{"marginLeft": "100px"}}>
<div style={{"fontSize":"16px","lineHeight":"1.8"}}>{currentObj.goodsName}-{currentObj.goodsId}</div>
<div style={{"lineHeight":"1.8"}}>售價:{currentObj.salePrice} 元</div>
<div style={{"clear": "both"}}></div>
</div>
</div>
</Link>
</SwipeAction>
---------------------