itsource

스크립트에서 인라인 HTML에 반응하지 않고 jsx를 사용할 수 있습니까?

mycopycode 2023. 4. 2. 10:25
반응형

스크립트에서 인라인 HTML에 반응하지 않고 jsx를 사용할 수 있습니까?

jsx와 같은 라이브러리를 사용하여 스크립트에서 다음과 같이 인라인 HTML을 사용할 수 있습니까?

<script src="jsx-transform.js"></script>
<script type="text/jsx">
define('component', function () {
   return (<div>test html code</div>);
});
</script>

JSX 파일을 작성하여 '짝퉁' 리액트 파일을 사용하여 HTML 페이지에 삽입할 수 있었습니다.

no-internal.internal.internal

/**
 * 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;
    }
};

그런 다음 jsx를 컴파일합니다.

test.tempx

const title = "Hello World";
document.getElementById('app').appendChild(
    <div>
        <h1>{title}</h1>
        <h2>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</h2>
    </div>
);

결과 컴파일된 '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")));

마지막으로 두 스크립트를 모두 포함하는 HTML 페이지입니다.

index.displaces를 표시합니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>no-react</title>
    <script src="no-react.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>

<script src="test.js"></script>

React는 React.createElement 등의 함수를 사용하여 JS에 JSX html 구문을 렌더링합니다.그러나 이 모든 것은 @babel/plugin-transform-react-jsx 플러그인으로 요약됩니다.이 플러그인은 다음과 같이 변환됩니다.

return(<div id="hello">Hello World</div>)

여기에...

return React.createElement('div', {id: 'hello'}, 'Hello World');

그러나 React.createElement를 사용자 고유의 기능으로 대체할 수 있습니다.상세한 것에 대하여는, https://babeljs.io/docs/en/next/babel-plugin-transform-react-jsx.html 를 참조해 주세요.

또한 nervjs, jsx-render, decku와 같이 정확하게 이를 수행하는 라이브러리도 살펴봐야 합니다.모두 반응 없이 JSX html 구문을 사용합니다.jsx-render와 같은 일부 제품은 JSX를 최종 JS로 변환하는 데만 초점을 맞추고 있습니다.

그 패키지의 작성자는, 다음의 URL 에 기사를 썼습니다.https://itnext.io/lessons-learned-using-jsx-without-react-bbddb6c28561

또한 Typescript는 다음을 사용할 경우 이 작업을 수행할 수 있습니다.직접 해본 적은 없어요

정리하면

React 없이 할 수 있지만 Babel 또는 Typescript 없이는 할 수 없습니다.

JSX는 문자열 기반의 템플릿 언어가 아니라 실제 JavaScript 함수 호출로 컴파일합니다.예를들면,

<div attr1="something" attr2="other">
  Here are some <span>children</span>
</div>

로 바뀌다.

React.createElement("div", {attr1: "something", attr2: "other"}, 
  "Here are some ", React.createElement("span", null, "children")
)

저도 이런 걸 찾고 있었어요컴포넌트 및 JSX를 간단한 프로젝트처럼 작성하는 방법.마음에 드는 것을 찾을 수 없었기 때문에, 이것을 구축했습니다.https://github.com/SagiMedina/Aviya#aviya 를 참조해 주세요.아마도, 당신의 고민도 해결할 수 있을 것입니다.

JSX를 JS 함수 호출로 변환하려면 무언가가 필요합니다.React는 Babel을 사용하여 이 작업을 수행합니다. 당신도 아마 이 작업을 하는 것이 가장 좋을 것입니다.

기본적으로 vhtml이라고 불리는 작업을 수행하는 Preact의 크리에이터가 만든 라이브러리가 있습니다.태그 행은 "VDOM 없이 HTML 문자열에 JSX/Hyperscript 렌터"입니다.

다음은 작성 시점의 Readme 사본입니다.

사용.

// import the library:
import h from 'vhtml';

// tell babel to transpile JSX to h() calls:
/** @jsx h */

// now render JSX to an HTML string!
let items = ['one', 'two', 'three'];

document.body.innerHTML = (
  <div class="foo">
    <h1>Hi!</h1>
    <p>Here is a list of {items.length} items:</p>
    <ul>
      { items.map( item => (
        <li>{ item }</li>
      )) }
    </ul>
  </div>
);

신규: "Sortof" 컴포넌트!

vhtml은 의도적으로 JSX를 Virtual DOM으로 변환하지 않고 HTML로 직접 시리얼화합니다.단, 기본 Pure Functional Components를 "템플릿 부분"으로 사용할 수도 있습니다.

vhtml이 JSX 태그 이름으로 지정된 함수는 해당 함수를 호출하고 {children, ...props}을(를) 전달합니다.이 시그니처는 react/preact의 Pure Functional Component와 동일하지만 children은 이미 시리얼화된HTML 문자열의 배열입니다.

이는 이러한 단순한 컴포넌트 또는 고차 컴포넌트로 컴포지션템플릿 수식자를 작성할 수 있음을 의미합니다.

다음은 컴포넌트를 사용하여 반복 항목을 캡슐화하는 이전 예제의 보다 복잡한 버전입니다.

항목 = ['1', '2';

const Item = ({ item, index, children }) => (
  <li id={index}>
    <h4>{item}</h4>
    {children}
  </li>
);

console.log(
  <div class="foo">
    <h1>Hi!</h1>
    <ul>
      { items.map( (item, index) => (
        <Item {...{ item, index }}>
          This is item {item}!
        </Item>
      )) }
    </ul>
  </div>
);

위의 출력은 다음 HTML 입니다.

<div class="foo">
  <h1>Hi!</h1>
  <ul>
    <li id="0">
      <h4>one</h4>This is item one!
    </li>
    <li id="1">
      <h4>two</h4>This is item two!
    </li>
  </ul>
</div>

셰프 패키지가 이걸 할 수 있을 것 같아요.Readme에서:

  • API를 사용하지 않고 JSX는 실제 DOM 요소로 자동 변환됩니다.

// babel.config.js

const plugins = [
  [
    '@babel/plugin-transform-react-jsx',
    {
      pragma: 'h',
      pragmaFrag: 'DocumentFragment',
    }
  ]
];

// ...

const {h} = require('dom-chef');

const handleClick = e => {
    // <a> was clicked
};

const el = (
    <div class="header">
        <a href="#" class="link" onClick={handleClick}>Download</a>
    </div>
);

document.body.appendChild(el);

인브라우저 JSX 변환Babel 매뉴얼을 참조할 수 있습니다.

당신이 원하는 것을 이룰 수 있지만, 그것은 생산에서 좌절되고 있다.

Jsx의 해석return (<div>test html code</div>);이런 거에 대해서return React.createElement('div', {...});

사용하지 않으면react.js브라우저는 무엇을 인식할 수 없습니다.React에러를 트리거합니다.

언급URL : https://stackoverflow.com/questions/30430982/can-i-use-jsx-without-react-to-inline-html-in-script

반응형