Javascript 如何访问onClick-in-react映射函数中的数据
我很好奇,人们如何能够访问map函数中的数据,以便在React中传递onClick函数中的函数时,可以在事件参数中使用它 这是我的handleClick函数。我想使用handleClick中的事件从map函数获得对“d”命名属性的访问权,如果有其他方法获得对变量“d”的访问权,那么我可以在handleClick中使用它,这将非常棒。我找不到这种情况的具体解决方案,所以我想知道是否可以得到一些帮助。谢谢Javascript 如何访问onClick-in-react映射函数中的数据,javascript,reactjs,Javascript,Reactjs,我很好奇,人们如何能够访问map函数中的数据,以便在React中传递onClick函数中的函数时,可以在事件参数中使用它 这是我的handleClick函数。我想使用handleClick中的事件从map函数获得对“d”命名属性的访问权,如果有其他方法获得对变量“d”的访问权,那么我可以在handleClick中使用它,这将非常棒。我找不到这种情况的具体解决方案,所以我想知道是否可以得到一些帮助。谢谢 // Gain access to the parameter data from the m
// Gain access to the parameter data from the map function
public handleClick(event: React.MouseEvent<HTMLAnchorElement>) {
console.log(event);
}
//从map函数访问参数数据
公共handleClick(事件:React.MouseEvent){
console.log(事件);
}
public render(){
返回(
{this.props.data.slice(0,MAX_RESULTS_LENGTH).map((d:any)=>(
{d.address}
))}
);
}
}
只需将其作为内联函数传递即可
public render() {
return (
<div className="">
{this.props.data.slice(0, MAX_RESULTS_LENGTH).map((d: any) => (
<a tabIndex={0} onClick={e => this.handleClick(e, d)} key={d.id}>
{d.address}
</a>
))}
</div>
);
}
}
public handleClick(event: React.MouseEvent<HTMLAnchorElement>, d: any) {
console.log(event, d);
}
public render(){
返回(
{this.props.data.slice(0,MAX_RESULTS_LENGTH).map((d:any)=>(
this.handleClick(e,d)}键={d.id}>
{d.address}
))}
);
}
}
public handleClick(事件:React.MouseEvent,d:any){
console.log(事件,d);
}
有没有更有效的方法?内联函数不是更低效吗。我在jsxNot中遇到了一个涉及渲染性能的错误。您可以将其封装在常规函数中。但这不会带来性能提升,更有效的方法是使用bind
this.handleClick.bind(this,d)
这部分内容无论是否已绑定(或不必绑定),但它允许您选择调用函数时发送的参数。
public render() {
return (
<div className="">
{this.props.data.slice(0, MAX_RESULTS_LENGTH).map((d: any) => (
<a tabIndex={0} onClick={e => this.handleClick(e, d)} key={d.id}>
{d.address}
</a>
))}
</div>
);
}
}
public handleClick(event: React.MouseEvent<HTMLAnchorElement>, d: any) {
console.log(event, d);
}