简体   繁体   English

反应,将prop作为函数参数传递

[英]React, pass prop as function argument

<div id="board" onClick={(event) => 
                         this.props.boardClicked(event)}>

I would like to pass a second argument trying something like this, but my syntax is off I think: 我想通过第二个参数尝试这样的事情,但是我认为语法不正确:

<div id="board" 
   onClick={(event, {this.props.activeCharacter}) =>
            this.props.boardClicked(event, {this.props.activeCharacter})}>

Simple change would be that because you are using an arrow function it is lexically bound automatically to the react compmponent instance, so you can use this within function. 简单的变化是,因为您使用的是箭头功能,它自动按词法绑定到react组件实例,因此您可以在函数内使用this Simply pass as an extra arg from within the function 只需从函数内部作为额外的arg传递

<div id="board" onClick={(event) => this.props.boardClicked(event, this.props.activeCharacter)}>

Using arrow functions in event handlers in react is a bad idea though because it creates an anonymous function, that will cause this component to unnecessarily always re-render which can hurt performance if component is used a lot 尽管在事件处理程序中使用箭头函数进行反应不是一个好主意,因为它创建了一个匿名函数,这将导致该组件不必要地总是重新渲染,如果大量使用该组件会影响性能。

You can overcome that by defining a handler on your class 您可以通过在类上定义处理程序来克服这一问题

onBoardClick = (event) => this.props.boardClicked(event, this.props.activeCharacter)

render = () => <div id="board" onClick={this.onBoardClick} />

Now you are passing the same function reference each time so no unnecessary re-renders but same click handler functionality 现在,您每次都传递相同的函数引用,因此无需重新渲染,而具有相同的单击处理程序功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM