如何从HTML执行React组件

时间:2019-01-05 20:29:32

标签: reactjs erb

我开始构建一个React组件来学习如何。我想将其嵌入到现有的html页面中(无论如何,还是erb),但是我不确定如何使它执行。

刷新页面不会执行任何操作或渲染react组件中的内容。控制台日志也不会出现,因此我猜测它没有执行。

// in main_control.js
var MainControl = React.createClass({
  render: function() {
    return <div>Something something Dark Side</div>;
    }
});

ReactDOM.render(
  <MainControl />,
  document.getElementById('main_control')
);

// in the html file
<head>
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src='/components/main_control.js' type='text/babel'>     
</script>
</head>


<h3>control for <%= @site.site_name %> </h3>


<div id="main_control"></div>

唯一显示的是标签中的内容

1 个答案:

答案 0 :(得分:1)

您接近了,这是创建无状态组件的方法:

const MainControl = () => {
    return <div>Something something Dark Side</div>
};

ReactDOM.render(
  <MainControl />,
  document.getElementById('main_control')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.1.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.1.1/umd/react-dom.production.min.js"></script>
<h3>control for <%= @site.site_name %> </h3>
<div id="main_control"></div>

这是创建全状态状态的方法:

class MainControl extends React.Component{
  render(){
      return <div>Something something Dark Side</div>
  }
}


ReactDOM.render(
  <MainControl />,
  document.getElementById('main_control')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.1.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.1.1/umd/react-dom.production.min.js"></script>
<h3>control for <%= @site.site_name %> </h3>
<div id="main_control"></div>

如果您想使用React动态生成站点名称:

const MainControl = ({ siteName }) => {
    return (
      <div>
        <h3>{siteName}</h3>
        <div>Something something Dark Side</div>
      </div>
    )
    
};

ReactDOM.render(
  <MainControl siteName='My website'/>,
  document.getElementById('main_control')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.1.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.1.1/umd/react-dom.production.min.js"></script>
<div id="main_control"></div>