- 由于我是 react 新手,所以我对隐藏/显示不太了解。
- 在我的页面中,我有切换按钮,当我单击该按钮时,会出现一个包含 3 个选项的容器。
- 当我点击任一选项时,会出现一个警告框。
- 当我单击警报框中的“确定”按钮时,整个容器应该隐藏。
- 工作演示:codesandboxdemo
- 代码:
.App {
font-family: sans-serif;
text-align: center;
}
.style1 {
cursor: pointer;
padding-top: 10px;
border-bottom-left-radius: 1px
}
.style1:hover{
background-color: #D3D3D3;
}
.box{
background-color:#eeeeee;
width:20%;
margin-top:1px;
}
class Foo extends Component {
state = { showing: false, };
handleClick()
{
alert("hi");
}
render() {
const { showing } = this.state;
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>toggle</button>
{ showing
? (
<div className="box">
<div className="style1" onClick={this.handleClick}>Action1</div>
<div className="style1" onClick={this.handleClick}>Action2</div>
<div className="style1" onClick={this.handleClick}>Action3</div>
</div>
)
: null
}
</div>
)
}
}
export default Foo;
最佳答案
最终输出:
以下是如何做到这一点,我使用确认
对话框而不是警报,因为它有一个确定
和取消
选项两者兼而有之,所以它会更加用户友好:
import React, { Component } from "react";
import "./styles.css";
class Foo extends Component {
state = { showing: false };
handleClick = () => {
if (window.confirm("Hide Div Emelent")) {
this.setState({ showing: false });
}
};
render() {
const { showing } = this.state;
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>
toggle
</button>
{showing ? (
<div className="box">
<div className="style1" onClick={this.handleClick}>
Action1
</div>
<div className="style1" onClick={this.handleClick}>
Action2
</div>
<div className="style1" onClick={this.handleClick}>
Action3
</div>
</div>
) : null}
</div>
);
}
}
export default Foo;
工作示例:Codesandbox
关于reactjs - 如何在reactjs中 "Hide a div by clicking alert box ok button",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65488352/