以下代码使用 React JS 在网页上显示图像列表:
this.searchResultsList = this.searchResults.map(function(photo){
return <div className="dataSetBox" key={photo.toString()}><img src={photo} alt="Image" height="350" width="450" margin="15px" border= "10" onClick={() => imageClick(id = "border")} /></div>;
})
当单击网页上的图像时,我希望该图像周围出现边框。 将会用黑色边框包围图像。
但是,我希望边框仅在单击图像后才出现。我上面的代码不起作用,并且收到 id 未定义的错误。知道如何修复它吗?
最佳答案
以下是如何管理此问题的示例。您需要一个状态变量来处理它。单击时它将自动切换边框。
const CSSVariables = {
border : {
border : '2px solid red'
},
noBorder : {
border : '2px solid transparent'
},
};
class TestJS extends React.Component {
constructor(props) {
super(props);
this.applyBorder = this.applyBorder.bind(this);
this.state = {
showBorder : false
}
}
applyBorder(){
this.setState(state => ({ showBorder: !state.showBorder }))
}
render() {
return(
<div id="root">
<img src="https://www.npmjs.com/static/images/avatars/Avatar2.svg" onClick={this.applyBorder} style={this.state.showBorder ? CSSVariables.border : CSSVariables.noBorder}/>
</div>
);
}
}
export default TestJS;
关于javascript - ReactJS:点击时创建图像ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49145006/