簡體   English   中英

在 html 上反應 JSX

[英]React JSX on html

我嘗試在簡單的 HTML 文件上插入反應。 https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project上有一個官方示例,但我不明白如何呈現 JSX 編碼組件以及如何將組件插入另一個組件:

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() {
    if (this.state.liked) {
      return "You liked this.";
    }

    // Display a "Like" <button>
    return <button onClick={() => this.setState({ liked: true })}>Like</button>;
  }
}

const domContainer = document.querySelector("#like_button_container");
ReactDOM.render(LikeButton, domContainer);

所以你可能已經按照指示將 React 和 ReactDOM 導入到你的 HTML 中:

<!-- depends where it's hosted -->
<script src="react.min.js"></script>
<script src="reactdom.min.js"></script>

然后你也將你的自定義 JS 添加到 HTML 中:

<!-- this goes right before the closing body tag -->
<script src="custom-like-button.js"></script>

最后,在您希望組件呈現的位置放置一個 HTML 元素,並確保它具有與 React 示例末尾的 querySelector 匹配的 id:

<div id="custom-like-button"></div>

對於嵌套組件,您可以將它們嵌套在頂級組件(被注入到 DOM 中的組件)的返回值中

class MyComponent extends React.Component {
  render() {
    return <LikeButton />
  }
}
class LikeButton extends React.Component {
  render () {
    return <button onClick={() => this.setState({ liked: true })}>Like</button>;
  }
}
// goes inside <div id="my-component"></div> in html
const domContainer = document.querySelector("#my-component");
ReactDOM.render(MyComponent, domContainer);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM