如何将React组件嵌入其他域? [英] How to embed react component on other domains?

查看:266
本文介绍了如何将React组件嵌入其他域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的React组件.我希望该组件用作插件或小部件.我已经从使用React& Webpack 并设法将我的Webpack设置如下:

I have created a simple React component. I want that component to use as a plugin or widget. I have taken help from Writing embeddable Javascript plugin with React & Webpack and manage to set my webpack as below:

output: {
    path: __dirname + '/dist',
    filename: './app/components/FirstWidgetIndex.js',
    publicPath: '/',
    library: 'tracking',
    libraryTarget: 'umd',
    umdNamedDefine: true,
  }

我的组件如下:

import React, { Component, PropTypes } from 'react';

export default class FirstWidget extends Component {

    constructor() {
        super();
    }

    render() {

        return (
            <div className="setting-fullpage">
                <p>React Widget</p>
            </div>
        )
    }
}

const mapStateToProps = state => {
    //
}

module.exports = FirstWidget

我的FirstWidgetIndex文件(webpack的入口)如下:

And my FirstWidgetIndex file (entry point of webpack) is as follows:

import React, { Component, PropTypes } from 'react';
import { render } from 'react-dom';
import App from './FirstWidget.js';

render(
  <App />,
  document.getElementById('app')
);

现在,我想将此FirstWidget添加为可嵌入的小部件.我在html文件中的第三方域上调用它,如下所示:

Now, I want to add this FirstWidget as an embeddable widget. I am calling it on third party domain in an html file as follows:

<html>
    <head>
        <script type="text/jsx" src="https://mydomain/firstWidget"></script>
    </head>
    <body>
        <p>Testing React Widget</p>
        <div id='app'></div>
    </body>
</html>

但是它没有在html页面上呈现我的窗口小部件.有人可以建议我是否想念任何东西吗?

But its not rendering my widget on the html page. Can anyone please suggest if I am missing anything?

推荐答案

您需要告知react将在哪里渲染,例如:

You need to tell where react will render, for example:

FirstWidget.js

import React, { Component } from 'react';

export default class FirstWidget extends Component {
  render () {
    return (
      <h1>Hello world</h1>
    );
  }
}

index.js

这是您在webpack中的入口点

This is your entry point in webpack

import React from 'react';
import { render } from 'react-dom';

import App from './FirstWidget.js';

render(
  <App />,
  document.getElementById('app')
);

在您的 index.html 中,您需要有一个带有app id的标签.

In your index.html you need to have a tag with app id.

<div id='app'></div>

注意:index.js中的代码必须与上面的代码相同,并且应该是Webpack配置中的入口点.

Note: The code in index.js needs to be like it's above and it should be the entry point in your webpack configuration.

这篇关于如何将React组件嵌入其他域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆