gpt4 book ai didi

javascript - 带参数的 React(组件)onClick 方法

转载 作者:太空宇宙 更新时间:2023-11-04 15:42:12 25 4
gpt4 key购买 nike

我在将参数放入函数时遇到问题。我尝试了在 Stack Overflow 上找到的几种解决方案,但没有成功。

这是我的代码:

function mapStateToProps(store) { return { un: store.measurement.unsaved, pat: store.patient.patients }; }

class MeasUnsaved extends Component{
constructor(){
super();
this.showBtn = this.showBtn.bind(this);
this.findPat = this.findPat.bind(this); this.createObj = this.createObj.bind(this);}
findPat(id){
let ps = this.props.pat.filter( p => (p.id === id) );
return ps[0];
}
createObj(){
let meas = [], i=0;
this.props.un.forEach( u => {
let pat = this.findPat(u.patId);
let k = { date: u.date, fnote: u.fnote, patId: u.patId, name: pat.lastName+' '+pat.name, pos: i };
i++;
meas.push(k);
});
return meas;
}
showBtn(val){
console.log(val);
}
render(){
const unsaved = this.createObj();
return (
<Well>
<fieldset>
<legend>Unsaved Measurement</legend>
<p>Unsaved Meas. will be lost after logout.</p>
{this.props.un.length === 0 && <p> You have 0 unsaved measurement </p>}
{this.props.un.length > 0 &&
<Table responsive>
<thead>
<tr><th>Date</th><th>Note</th><th>Patient</th><th>Actions</th></tr>
</thead>
<tbody>
{
unsaved.map(function(u){
return (
<tr key={u.date+u.patId.toString()}>
<td>{u.date}</td>
<td>{u.fnote}</td>
<td>{u.name}</td>
<td><Button bsSize="small" onClick={this.showBtn(u.pos)}>Show</Button></td>
</tr>
);
})
}
</tbody>
</Table>
}
</fieldset>
</Well>
);
}
} export default connect(mapStateToProps)(MeasUnsaved) ;

这是错误:

ERROR: Uncaught Uncaught TypeError: Cannot read property 'showBtn' of undefined at onClick

最佳答案

你有两个问题;

  1. 您在“map”内使用“this” - 请参阅 "this" is undefined inside map function Reactjs

  2. 您在每一行上执行 this.showBtn,您想要的是将函数作为参数传递 - 这应该足够了:

    onClick={() => this.showBtn(u.pos)}

关于javascript - 带参数的 React(组件)onClick 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43786103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com