Can I use jsx without React to inline HTML in script?

后端 未结 8 1701
既然无缘
既然无缘 2021-01-31 02:20

Can I use inline HTML in a script as below by using a library like jsx:




        
8条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 03:06

    I was able to write JSX files and inject them into an HTML page using a 'fake' React file.

    no-react.js

    /**
     * Include this script in your HTML to use JSX compiled code without React.
     */
    
    const React = {
        createElement: function (tag, attrs, children) {
            var element = document.createElement(tag);
    
            for (let name in attrs) {
                if (name && attrs.hasOwnProperty(name)) {
                    let value = attrs[name];
                    if (value === true) {
                        element.setAttribute(name, name);
                    } else if (value !== false && value != null) {
                        element.setAttribute(name, value.toString());
                    }
                }
            }
            for (let i = 2; i < arguments.length; i++) {
                let child = arguments[i];
                element.appendChild(
                    child.nodeType == null ?
                        document.createTextNode(child.toString()) : child);
            }
            return element;
        }
    };
    

    Then compile your jsx.

    test.jsx

    const title = "Hello World";
    document.getElementById('app').appendChild(
        

    {title}

    This is a template written in TSX, then compiled to JSX by tsc (the Typescript compiler), and finally injected into a web page using a script

    );

    Resulting compiled 'test.js'

    var title = "Hello World";
    document.querySelector('#app').appendChild(React.createElement("div", null,
        React.createElement("h1", null, title),
        React.createElement("h2", null, "This is a template written in TSX, then compiled to JSX by tsc (the Typescript compiler), and finally" + " " + "injected into a web page")));
    

    And finally, the HTML page that includes both scripts.

    index.html

    
    
    
        
        no-react
        
    
    
    

提交回复
热议问题