我已经使用react创建了一个基本模态,并且没有任何库,并且运行良好,现在,当我单击模态外部想要关闭模态时
这是CodeSandbox实时预览
我的index.js:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
showModal: false
};
}
handleClick = () => {
this.setState(prevState => ({
showModal: !prevState.showModal
}));
};
render() {
return (
<>
<button onClick={this.handleClick}>Open Modal</button>
{this.state.showModal && (
<div className="modal">
I'm a modal!
<button onClick={() => this.handleClick()}>close modal</button>
</div>
)}
</>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
答案 0 :(得分:1)
有关工作示例,请参见附件Codesandbox。
您快到了。首先,您需要在public int solution(int A) {
var charArray=A.ToString().ToCharArray();
StringBuilder sb=new StringBuilder();
for(int i=0,j=charArray.Length-1; i<=j; i++,j--)
{
//Console.WriteLine(" ("+i+","+j+")");
sb.Append(charArray[i]);
if(i!=j)
sb.Append(charArray[j]);
//Console.WriteLine(sb.ToString());
}
return (Int32.Parse(sb.ToString()));
}
中执行一个回调函数,该函数将向文档添加handleClick()
方法:
closeMenu
然后在 handleClick = event => {
event.preventDefault();
this.setState({ showModal: true }, () => {
document.addEventListener("click", this.closeMenu);
});
};
内切换状态:
closeMenu()
每当您在组件外部单击时,它将关闭它。 :)
答案 1 :(得分:0)
使用ref
会有些棘手
观看此CodeSandBox
答案 2 :(得分:0)
这对我有用:
需要使用e.stopPropagation
来防止循环
handleClick = e => {
if (this.state.showModal) {
this.closeModal();
return;
}
this.setState({ showModal: true });
e.stopPropagation();
document.addEventListener("click", this.closeModal);
};
然后:
closeModal = () => {
this.setState({ showModal: false });
document.removeEventListener("click", this.closeModal);
};
希望会有所帮助