我的应用程序组件:
import React, { Component } from 'react';
import Library from './Library'
class App extends Component {
state = {
library: storeGet() || {},
lib_img_selected : null
};
selectedLibImgHandler = (url) => {
console.log('url', url)
};
render() {
return (
<div className="container">
<div className="row">
<Library mylibrary={this.state.library} onSelectedImage={this.selectedLibImgHandler} />
</div>
</div>
);
}
}
export default App;
我有这个组件库:
import React, { Component } from 'react';
import Card from './Card'
class Library extends Component {
imageSelected = (udsUrl) =>{
console.log('clicked')
}
getPreviews = () => {
// console.log('this.props.library', this.props.mylibrary)
var self = this;
var cards = Object.keys(this.props.mylibrary).map(function (key, index) {
let x = self.props.mylibrary[key];
let card = {}
card.uid = x.id
card.title = x.customImageName || 'Img ' + index
card.src = 'http://myurl';
card.url = 'http://....'
return card
});
return cards;
}
render() {
return (
<div className="row">
<div className="jumbotron" >
<h1>Library</h1>
{this.getPreviews().map(card => <Card key={card.uid} {...card} onClick={this.imageSelected(card.url) }/>)}
</div>
</div>
)
}
}
export default Library;
卡片是这样的:
import React from 'react';
const Card = (props) => {
return (
<div className='card-box'>
<div className='card-image'>
<img src={props.src} alt="" className={props.orientation} />
</div>
<div>{props.title}</div>
</div>
);
};
export default Card;
我不明白为什么
onClick={this.imageSelected(card.url)
每个呈现的Card组件都会被触发,然后当我单击Card时没有任何反应。
我认为我缺少关于React的渲染和功能绑定的一些核心概念
答案 0 :(得分:3)
onClick
需要一个函数,即您使用函数的方式,是将imageSelected的返回值与不是函数的onClick关联,因此在每个渲染器上都执行该函数。像这样使用
onClick={() => this.imageSelected(card.url)}
此外,click
事件已在组件上注册,而是作为道具传递给组件。您需要将点击事件分配给卡片,例如
const Card = (props) => {
return (
<div className='card-box' onClick={props.onClick}>
<div className='card-image'>
<img src={props.src} alt="" className={props.orientation} />
</div>
<div>{props.title}</div>
</div>
);
};
查看此答案以获取更多详细信息Applying className/onClick/onChange not working on Custom React Component
通常,如果您需要传递从父母传递来的所有道具,则可以使用以下语法:
<div className='card-box' {...props}>
对所有props
进行销毁将确保道具获得通过,并且您无需为每个道具手动进行操作。