简体   繁体   English

做出反应。 换图片 onclick

[英]React. Change pictures onclick

I'm creating a page with many pictures.我正在创建一个包含许多图片的页面。 If you click on one picture, it should change.如果你点击一张图片,它应该会改变。 I tried to make it with toggling state but it works not the way I want: it changes all the photos if you click on just one.我试图通过切换 state 来实现它,但它不是我想要的方式:如果你只点击一张,它会改变所有的照片。

Then I tried to use this code but it doesn't work at all (it doesn't even log)然后我尝试使用此代码,但它根本不起作用(它甚至没有记录)

 import bag1 from "../../img/bag1.jpg" onClickHandler = (e) => { let src = (e.target.src || e.srcElement.src); if(src=={bag0}) { console.log("It works") } } render(){ return( <div className="main"> <img onClick={this.onClickHandler} src={bag0}/> </div> ) }

Could you tell me, what's wrong here?你能告诉我,这里有什么问题吗? Or do you know, how I can make another way?或者你知道,我怎样才能另辟蹊径?

Here is a working example if this helps如果这有帮助,这是一个工作示例

 class App extends React.Component { constructor(props) { super(props); this.defaultImage = 'https://cdn0.iconfinder.com/data/icons/30-hardware-line-icons/64/Search-64.png'; this.state = { selectedImage: this.defaultImage, } this.onClickHandler = this.onClickHandler.bind(this); } onClickHandler(e) { const src = e.target.src; if(src === this.defaultImage) { this.setState({ selectedImage: 'https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/search-64.png' }); } } render() { return(<div className="main"> <img onClick={this.onClickHandler} src={this.state.selectedImage} /> </div>); } } ReactDOM.render(<App />, document.getElementById('root'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root" />

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

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