我正在处理React项目,无法将值传递给事件处理程序,然后更新状态以包含该值,以便以后可以使用条件渲染。
这是我的构造器/状态:
constructor(props) {
super(props);
this.state = {
waterImg: `https://thumbs.dreamstime.com/b/small-water-drop-splash-crown-14698311.jpg`,
fireImg: `http://d.stockcharts.com/img/articles/2017/09/15057727422401691285382.jpg`,
image: ""
};
}
我有两个div,红色和蓝色。单击红色时,我想将this.state.image
更新为包含“ fire”,单击蓝色时,我想将其更新为“ water”。然后,我想使用条件渲染来渲染适当的火/水图像。
handleClick = e => {
this.setState({
image: // Want to update image state to either fire or water depending on which div is clicked
});
};
render() {
return (
<Styles>
// How do I pass handleClick the value fire from here?
<div className="red" onClick={this.handleClick} />
// How do I pass handleClick the value water from here?
<div className="blue" onClick={this.handleClick} />
{
this.state.image === "water" ?
<img src={this.state.waterImg} height="100" alt="water pic"/>
: ""
}
{
this.state.image === "fire" ?
<img src={this.state.fireImg} height="100" alt="fire pic"/>
: ""
}
</Styles>
);
}
}
主要是我很难将值从onClick函数传递到handleClick函数。我已经尝试过这样的事情:
<div className="red" onClick={(e) => this.handleClick(e)} />
但是我仍然不知道必须将值传递给handleClick,然后更新状态以包含该值。
这里是Code Sandbox
答案 0 :(得分:0)
有几种方法可以做到这一点:
.bind()
绑定:<div className="red" onClick={this.handleClick.bind(null, this.state.fireImg)} />
<div className="blue" onClick={this.handleClickthis.handleClick.bind(null, this.state.waterImg)} />
handleClick = (image, e) => {
this.setState({ image });
};
<div className="red" onClick={() => this.setState({image: this.state.fireImg})} />
<div className="blue" onClick={() => this.setState({image: this.state.waterImg})} />
className
(或任何其他属性)来找出单击了哪个元素:handleClick = e => {
let image;
if(e.target.className === "red")
image = this.state.fireImg;
else
image = this.state.waterImg;
this.setState({image});
};
答案 1 :(得分:0)
您可以使用currentTarget.getAttribute()
来获取值
handleClick(e) {
const name = e.currentTarget.getAttribute("name");
if (name === 'red') this.setState({image: this.state.fireImg})
else if (name === 'blue') this.setState({image: this.state.waterImg})
}
render() {
return (
<Styles>
<div className="one" name="red" onClick={this.handleClick} />
<div className="two" name="blue" onClick={this.handleClick} />
<div className="three" />
</Styles>
);
}