Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ReactでDecoratorsを使う

 ReactでDecoratorsを使う

React Beer Bash! (https://react-beer-bash.connpass.com/event/78112/) でLTしました

Masashi Hirano

March 07, 2018
Tweet

More Decks by Masashi Hirano

Other Decks in Programming

Transcript

  1. ྫ͑͹ϓϩύςΟͷ௥Ճ function name(name) { return function (target) { target.prototype.name =

    name; } } ΫϥεʹOBNFͱ͍͏ϓϩύςΟΛ௥Ճ͢Δ ؔ਺Λఆٛ
  2. @name(“React") class App extends React.Component { ɹrender() { return (

    <div> Hello, {this.name} </div> ); } } ReactDOM.render(<App />, document.getElementById('app')); ͜ͷίϯϙʔωϯτࣗମ͸OBNFͱ͍ ͏ϓϩύςΟ͸͍࣋ͬͯͳ͍ σίϨʔλʔ
  3. react-redux class MyFancyComponent extends React.Component { // ׂѪ } const

    mapStateToProps = (state) => { return { users: state.users }; } const mapDispatchToProps = (dispatch, ownProps) { return {// ׂѪ} } export default connect(mapStateToProps, mapDispatchToProps)(MyFancyComponent) SFBDUSFEVYͷDPOOFDUؔ਺ɻ Α͘ݟΔ࢖͍ํ
  4. react-redux @connect(mapStateToProps, mapDispatchToProps) class MyFancyComponent extends React.Component { // ׂѪ

    } const mapStateToProps = (state) => { return { users: state.users }; } const mapDispatchToProps = (dispatch, ownProps) { return {// ׂѪ} } DPOOFDUΛσίϨʔλʔͱͯ͠$MBTT ʹ෇͚Δ͜ͱ͕Ͱ͖Δ
  5. MobX class Timer { constructor() { extendObservable(this, { start: Date.now(),

    current: Date.now(), get elapsedTime() { return (this.current - this.start) }, tick: action(function() { this.current = Date.now() }) }) } } FYUFOE0CTFSWBCMFؔ਺Λ࢖ͬͯ PCTFSWBCMFʹ͍ͯ͠Δ
  6. MobX class Timer { @observable start = Date.now(); @observable current

    = Date.now(); @computed get elapsedTime() { return (this.current - this.start) } @action tick() { this.current = Date.now() } } σίϨʔλʔΛ࢖ͬͯ؆ܿʹॻ͚Δ
  7. react-log-decorator import logger from 'react-log-decorator'; const log = logger(process.env.NODE_ENV ===

    'development'); export default class MyComponent extends Component { @log render() { return ( <div> <input type="text" onChange = {this.props.onChange} /> <p>{this.props.message}</p> </div> ) } } ࣮ߦ࣌ʹQSPQT΍TUBUFͷ಺༰Λίϯ ιʔϧʹද͍ࣔͨ͠ϝιουʹ෇͚Δ
  8. pure-deep-equal class Test extends React.Component { shouldComponentUpdate(nextProps, nextState) { return

    !deepEqual(this.props, nextProps) || !deepEqual(this.state, nextState); } render() { return <span>{this.props.message}</h1> } } TIPVME$PNQPOFOU6QEBUFͷதͰ EFFQDPNQBSF
  9. pure-deep-equal @PureDeepEqual class Test extends React.Component { render() { return

    <span>{this.props.message}</h1> } } TIPVME$PNQPOFOU6QEBUFΛ࣮૷͠ ͳͯ͘΋σίϨʔλؔ਺͕EFFQ DPNQBSFͯ͘͠ΕΔ