问题
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,
}
And my component is as below:
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
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')
);
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>
But its not rendering my widget on the html
page. Can anyone please suggest if I am missing anything?
回答1:
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
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')
);
In your index.html you need to have a tag with 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.
来源:https://stackoverflow.com/questions/49171112/how-to-embed-react-component-on-other-domains