![](/img/trans.png)
[英]Pass prop value as a parameter in an arrow function in an event handler onClick() in React
[英]React: Pass value of HTML element to event handler onClick
我正在做一個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,然后更新狀態以包含該值。
這是一個代碼沙箱
有幾種方法可以做到這一點:
.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});
};
您可以使用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>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.