javascript 单击时更改图像 - React
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51480885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change image on click - React
提问by Sagiv b.g
So for example this is my view:
例如,这是我的观点:
<div>
<img src='../../minus.png' />
</div>
Now I want to make that on each click the image changes from plus.pngto minus.png.
现在我想在每次单击时将图像从 更改plus.png为minus.png。
So, click once: minus.png => plus.png, click again: plus.png => minus.png, and so on. How can I make this?
因此,单击一次:minus.png => plus.png,再次单击:plus.png => minus.png,依此类推。我怎样才能做到这一点?
回答by Sagiv b.g
This can be achieved with a simple toggle handler:
这可以通过一个简单的切换处理程序来实现:
const imagesPath = {
minus: "https://images.vexels.com/media/users/3/131484/isolated/preview/a432fa4062ed3d68771db7c1d65ee885-minus-inside-circle-icon-by-vexels.png",
plus: "https://cdn3.iconfinder.com/data/icons/glypho-generic-icons/64/plus-big-512.png"
}
class App extends React.Component {
state = {
open: true
}
toggleImage = () => {
this.setState(state => ({ open: !state.open }))
}
getImageName = () => this.state.open ? 'plus' : 'minus'
render() {
const imageName = this.getImageName();
return (
<div>
<img style={{maxWidth: '50px'}} src={imagesPath[imageName]} onClick={this.toggleImage} />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Edit
Note that I passed a function parameter for setStatebecause my new state depends on the old state. You can read more about it in the docs
编辑
请注意,我传递了一个函数参数,setState因为我的新状态依赖于旧状态。您可以在文档中阅读更多相关信息
回答by Marvin Fischer
Assuming this is inside the render function:
假设这是在渲染函数中:
<div>
<img onClick={() => {this.setState({clicked: true})}
src={'../../' + (this.state.clicked ? 'plus' : 'minus') + '.png'}} />
</div>

