jsx事件获取event对象

文章参考

  1. 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>
	)
}

二、 箭头函数获取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>
        );
	}
}

三、使用高阶函数获取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>

猜你喜欢

转载自blog.csdn.net/hbiao68/article/details/83580039
今日推荐