代码之家  ›  专栏  ›  技术社区  ›  AConsumer

Javascript:-如何将表中的值传递给onClick处理程序以实现删除功能

  •  0
  • AConsumer  · 技术社区  · 8 年前

    在onClick上,我试图调用delete函数。我需要的是tableItem的id值,我可以在UI中看到该id,但无法访问该id以删除特定行。场景是:单击->删除fn->使用id->删除该行。 我只需要身份证就可以了。我无法将其引入删除功能。

    import React from 'react';
    
    
    
    
    
    export default class TradeTable extends React.Component {
    
    	delete = (event) => {
    		event.preventDefault();
    		
    		console.log(event.target.value+"wdccerfec")
    	
    		//I just need the value of table item id 
    
    
    	}
    	render() {
    
    
    		var tableData = this.props.store.arr;
    
    
    
    		return <div className="panel panel-default">
    	
    			<div className="panel-body tradeComponent div-background table-responsive">
    				<table className="table table-striped tb div-lightbackground">
    
    					<thead className="thead-dark ">
    						<tr>
    							<th>Commodity</th>
    							<th>Date</th>
    							<th>Side</th>
    							<th>Qty (MT)</th>
    							<th>Price (MT)</th>
    							<th>CounterParty</th>
    							<th>Location</th>
    							<th></th>
    						</tr>
    					</thead>
    					<tbody>
                     //Trade data is an array of objects
    						{
    							tableData.map(tableItem => {
    								return (
    									<tr>
    										<td>{tableItem.tradeDate}</td>
    										<td>{tableItem.commodity}</td>
    										<td>{tableItem.side}</td>
    										<td>{tableItem.quantity}</td>
    										<td>{tableItem.price}</td>
    										<td>{tableItem.counterparty}</td>
    										<td>{tableItem.location}</td>
    										<td>{tableItem.id}</td>
    										<td>
    
    											
    
    <button type='submit' className="btn btn-primary table-style" value={tableItem.id} onClick={this.delete}  >
        												<span className="glyphicon glyphicon-trash" aria-hidden="true"></span>
    											</button>
    
    										</td>
    									</tr>)
    							})
    						}
    
    					</tbody>
    				</table>
    			</div>
    		</div>
    	}
    }
    2 回复  |  直到 8 年前
        1
  •  1
  •   Liam    8 年前

    您需要通过onClick按钮传递id

    onClick={this.delete.bind(this, tableItem.id)}
    

    然后

    delete = (id) => {
    
        console.log('Clicked item', id)
    }
    
        2
  •  0
  •   Chotala Paresh    8 年前
    onClick={() => this.delete(tableItem.id)}
    

    正在工作请参见 working demo