React.js: how to decouple jsx out of JavaScript

前端 未结 5 1200
你的背包
你的背包 2021-01-30 00:08

Is there any way to move the jsx from a component\'s render function to a separate file? If so, how do I reference the jsx in the render function?

5条回答
  •  不要未来只要你来
    2021-01-30 00:46

    One problem with moving templates into a separate file is that if you use handlers like:

    var myTemplate = (
        
    );

    and then in your component you use:

    render: function() {
        return myTemplate;
    }
    

    the generated template code will call this.handleSubmit(), so the "this" will be wrong and the handlers won't work. What you need to do is put them in a function, like this:

    var myTemplate = function() {
        return (
            
    ); };

    then in your component's render function, you need to bind it to 'this' correctly, then call it, like this:

    render: function() {
        return myTemplate.bind(this)();
    },
    

    Now you can put that template definition anywhere, in a separate file or however you want to structure and reference your own code. (power to you! Don't listen to these crazy prescriptive frameworks! :) )

提交回复
热议问题