Can React.js autorun be enabled for a React class model

According to this blog post , which restricts all methods React.createClassto is this not built into the React class model.

Is it possible to enable by default ?

I know that you can use the this.someMethod = this.ticksomeMethod.bind(this);trick to do it manually, but is it possible to do this for all methods ? Or am I forced to write bindfor all methods?

Sample code that I have now:

import MessageStore from '../stores/MessageStore.js';

export default class Feed extends React.Component {
   constructor() {
      this.state = {messages: MessageStore.getAll()}
      //can I avoid writing this for every single method?
      this._onChange = this._onChange.bind(this); 
   }

   _onChange() {
       this.setState({messages: MessageStore.getAll()});
   };

   // componentDidMount, componentWillUnmount and render methods ommited
}
+4
source share
3 answers

There is no activation function in React activation that does this. This is simply not an option.

- bind , , , , ( , , , , , ).

, bind , , JavaScript, .

+2

, @decorator. JavaScript- ES2015 stage-0 Babel, ! :

import autobind from 'autobind-decorator'
// (...)
<li onClick={ this.closeFeedback }>Close</li>
// (...)
@autobind
closeFeedback() {
  this.setState( { closed: true } );
}

, . :

npm install --save-dev babel-preset-stage-0
npm install --save-dev babel-plugin-react-transform
npm install --save-dev babel-plugin-transform-decorators-legacy
npm install --save-dev autobind-decorator

:

npm install --save-dev babel-preset-stage-0 babel-plugin-react-transform babel-plugin-transform-decorators-legacy autobind-decorator

.babelrc webpack.config.js , :

query: {
  presets: ['es2015', 'react', 'stage-0'],
  plugins: [['transform-decorators-legacy']]
}

( , .babelrc root node .)

!

+2

If you do not want or cannot yet use the babel decorator syntax. You can define the auto-detection function and add the boiler plate line to your class for automatic reference.

function autobind(target) { // <-- Define your autobind helper
    for (let prop of Object.getOwnPropertyNames(Object.getPrototypeOf(target))) {
        if (typeof target[prop] !== 'function') {
            continue;
        }
        if (~target[prop].toString().replace(/\s/g, '').search(`^${prop}[(][^)]*[)][{;][\'\"]autobind[\'\"];`)) {
            target[prop] = target[prop].bind(target);
        }
    }
}

class Test {
    constructor() {
        autobind(this); // <- single line of boilerplate
        this.message = 'message';
    }
    method1(){ return this.method2(); }
    method2(){ console.log(this.message);}
    _handleClick() { 'autobind'; // <-- autobind searches for functions with 'autobind' as their first expression.
        console.log(this.message);
    }
}

let test = new Test();
let _handleClick = test._handleClick;
_handleClick();
Run codeHide result
0
source

All Articles