例如,这是我的观点:
<div>
<img src='../../minus.png' />
</div>
现在,我要使每次单击使图像从plus.png
变为minus.png
。
因此,单击一次:minus.png => plus.png
,再次单击:plus.png => minus.png
,依此类推。我该怎么做?
答案 0 :(得分:7)
这可以通过简单的切换处理程序来实现:
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>
修改
请注意,我为setState
传递了一个函数参数,因为我的新状态取决于旧状态。您可以在docs
答案 1 :(得分:0)
在按钮上单击此示例代码,单击以更改条件以呈现img src:
import React from "react";
import "./styles.css";
import { Card, CardImg, CardBody, Button } from "reactstrap";
class App extends React.Component {
constructor() {
super();
this.state = {
loginState: true
};
}
render() {
let sessonState;
let imgurl;
if (this.state.loginState) {
sessonState = "Logged In";
imgurl = "https://picsum.photos/id/237/200/300";
} else {
imgurl = "https://picsum.photos/seed/picsum/200/300";
sessonState = "Logged Out";
}
return (
<div>
<h1>Session {sessonState}!!</h1>
<br />
<div className="container">
<div className="row">
<div className="col-md-4">
<Card className="shadow">
<CardImg top width="100%" src={imgurl} alt="Card image cap" />
<CardBody>
<Button
className="shadow-sm btn "
onClick={() => {
this.setState({
loginState: false
});
console.log(`${imgurl}`);
}}
>
Button
</Button>
</CardBody>
</Card>
</div>
</div>
</div>
</div>
);
}
}
export default App;
答案 2 :(得分:-1)
假设这是在render函数内部:
<div>
<img onClick={() => {this.setState({clicked: true})}
src={'../../' + (this.state.clicked ? 'plus' : 'minus') + '.png'}} />
</div>