我正在尝试将一个on click函数添加到从数组映射的列表标记中,即:
{this.props.addresses.map((address, index) =>
<li key={`address-${index}`} onClick={this.addressClick}>{address.prediction}</li>
)}
addressClick在构造函数中定义如下:
constructor (props) {
super(props)
this.addressClick = this.addressClick.bind(this)
}
并且像这样的类中的函数
addressClick () {
console.log('Clicked')
}
当我点击我的列表标签时没有任何反应,我没有看到任何控制台声明。
答案 0 :(得分:2)
将此绑定到地图方法:
{this.props.addresses.map((address, index) =>
<li key={`address-${index}`} onClick={this.addressClick}>{address.prediction}</li>
).bind(this)}
答案 1 :(得分:0)
您可以通过将索引传递给另一个函数然后调用addressClick()
来实现此目的。
function clickListener ( index ) {
var clickedAddress = addresses[index];
addressClick(clickedAddress.prediction);
}
{this.props.addresses.map((address, index) =>
<li key={`address-${index}`} onClick={`clickListener(${index})`}</li>
)}
答案 2 :(得分:0)
除非我遗漏了某些内容,否则您的代码应该有效。这适用于例如:
const arr = [1,2,3,4]
class App extends Component {
constructor(props) {
super(props)
this.addressClick = this.addressClick.bind(this)
}
addressClick () {
console.log('Clicked')
}
render() {
return (
<ul>
{arr.map((address, index) =>
<li key={`address-${index}`} onClick={this.addressClick}>{address}</li>
) }
</ul>
)
}
}