gpt4 book ai didi

javascript - 如何在其他域中嵌入 React 组件?

转载 作者:行者123 更新时间:2023-11-30 14:44:25 24 4
gpt4 key购买 nike

我创建了一个简单的 React 组件。我希望该组件用作插件或小部件。我已经从Writing embeddable Javascript plugin with React & Webpack获得了帮助并设法如下设置我的 webpack:

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的入口点)如下:

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

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

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

<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 页面上呈现我的小部件。如果我遗漏了什么,有人可以提出建议吗?

最佳答案

你需要告诉 react 将在哪里渲染,例如:

FirstWidget.js

import React, { Component } from 'react';

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

index.js

这是你在 webpack 中的入口点

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

import App from './FirstWidget.js';

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

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

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

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

关于javascript - 如何在其他域中嵌入 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49171112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com