➡️ 즉, class component, didMount, render 필요없음❗
import React from "react";
class App extends React.Component {
state = {
count: 0
};
modify = n => {
this.setState({ count: n });
};
render() {
const { count } = this.state;
return (
<>
<div>{count}</div>
<button onClick={() => this.modify(count + 1)}>Add</button>
</>
);
}
}
export default App;
import React, { useState } from "react";
const App = () => {
const [count, setCount] = useState(0);
return (
<>
{count}
<button onClick={() => setCount(count + 1)}>Add</button>
<button onClick={() => setCount(count - 1)}>Minus</button>
</>
);
};
export default App;
import React, { createRef, useEffect } from "react";
function clickOutside(fn) {
const ref = createRef();
const handleClick = e => {
if (!ref.current.contains(e.target)) {
fn();
}
};
useEffect(() => {
document.addEventListener("click", handleClick);
}, []);
return ref;
}
function App() {
const onClickOutside = () => {
console.log("Outside");
};
const ref = clickOutside(onClickOutside);
return (
<div className="App">
<div ref={ref}>
<h1>Hello Tia</h1>
<h3>This should be a popup</h3>
</div>
<input type="text" />
</div>
);
}
export default App;