Created
May 18, 2020 12:45
-
-
Save sangkukbae12/a4fc002170c3bcaeab891426316b95fc to your computer and use it in GitHub Desktop.
react state injection history
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// HOCs | |
function WithCount(Component) { | |
return class withCount extends React.Components { | |
state = { count: 0 } | |
increment = () => { | |
this.setState((state) => ({ count: state.count + 1 })) | |
} | |
decrement = () => { | |
this.setState((state) => ({ count: state.count - 1 })) | |
} | |
render() { | |
return ( | |
<Component | |
{...this.props} | |
{...this.state} | |
increment={this.increment} | |
decrement={this.decrement} | |
/> | |
) | |
} | |
} | |
} | |
class MyCounter extends React.Component { | |
render() { | |
return ( | |
<div>Count: {this.props.count}</div> | |
<div> | |
<button onClick={this.props.increment}>+</button> | |
<button onClick={this.props.decrement}>-</button> | |
</div> | |
) | |
} | |
} | |
MyCounter = withCount(MyCounter) | |
expoer default MyCounter | |
// Render Props | |
class WithCount extends React.Component { | |
state = { count: 0 } | |
increment = () => { | |
this.setState((state) => ({ count: state.count + 1 })) | |
} | |
decrement = () => { | |
this.setState((state) => ({ count: state.count - 1})) | |
} | |
render() { | |
return this,props.children( | |
{ | |
count: this.state.count, | |
increment: this.increment, | |
decrement: this.decrement | |
} | |
) | |
} | |
} | |
class MyCounter extends React.Component { | |
render() { | |
return ( | |
<WithCount> | |
{({ count, increment, decrement }) => ( | |
<div> | |
<div>Count: {count}</div> | |
<div> | |
<button onClick={increment}>+</button> | |
<button onClick={decrement}>-</button> | |
</div> | |
</div> | |
</WithCount> | |
) | |
} | |
} | |
MyCounter = withCount(MyCounter) | |
export default MyCounter | |
// Hooks | |
function useCount() { | |
const [count, setCount] = React.useState(0) | |
increment = React.useCallback(() => { | |
setCount((preCount) => preCount + 1) | |
}, []) | |
decrement = React.useCallback(() => { | |
setCount((preCount) => preCount - 1) | |
}, []) | |
return [ count, increment, decrement ] | |
} | |
function MyCounter() { | |
const { count, increment, decrement } = useCount() | |
return ( | |
<div> | |
<div>Count: {count}</div> | |
<div> | |
<button onClick={increment}>+</button> | |
<button onClick={decrement}>-</button> | |
</div> | |
</div> | |
) | |
} | |
export default MyCounter | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment