React.js: how to decouple jsx out of JavaScript

前端 未结 5 1150
你的背包
你的背包 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:31

    If you don't use any module system, i.e. rely on script tags only, simple expose your JSX component in a global variable and use it when you need :

    // component.js
    var Component = React.createClass({ /* your component */ });
    // main.js
    React.renderComponent(Component({}), domNode);
    

    Note : the script tag for component.js must appear before the script tag for main.js.

    If you use a Commonjs-like module system like Browserify, simply export your component definition and require it when you need it.

    // component.js
    var React = require("react");
    module.exports = React.createClass({ /* your component */ });
    // main.js
    var Component = require("component.js");
    React.renderComponent(Component({}), domNode);
    

提交回复
热议问题