我有一个带有webpack配置的可嵌入react小部件,下面是将嵌入客户端的脚本标记。
<script>
(function (w, d, s, o, f, js, fjs) {
w['simple-widget'] = o; w[o] = w[o] || function () { (w[o].q = w[o].q || []).push(arguments) };
js = d.createElement(s), fjs = d.getElementsByTagName(s)[0];
js.id = o; js.src = f; js.async = 1; fjs.parentNode.insertBefore(js, fjs);
}(window, document, 'script', 'w1', 'widget.js'));
w1('init', { targetElementId: 'simple-widget', message: "some string" });
</script>
如何捕获
message: "some string"
并发送它进行反应?
下面是我的apiHandle 代码
function apiHandler(api, params) {
if (!api) throw Error("API method required");
api = api.toLowerCase();
let config = window[widgetConfigName];
switch (api) {
case "init":
config = Object.assign({}, config, params);
window[widgetConfigName] = config;
// get a reference to the created widget component so we can
// call methods as needed
widgetComponent = React.createRef();
ReactDOM.render(
<Widget ref={widgetComponent} />,
document.getElementById(config.targetElementId)
);
break;
case "message":
console.log("switch case message");
// Send the message to the current widget instance
widgetComponent.current.setMessage(params);
break;
default:
throw Error(`Method ${api} is not supported`);
}
}
下面是我的react Wideget.js组件
class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
message: null,
};
}
render() {
console.log(this.state);
return (
<div className="main_container">
{message}
</div>
);
}
}
如果simple-widget
元素存在于DOM元素中,则可以从该元素获取message
属性。
class Widget extends React.Component {
constructor(props) {
super(props);
this.state = {
message: null,
};
}
componentDidMount() {
const widgetElement = document.getElementById('simple-widget');
this.setState({message: widgetEelement.message})
}
render() {
return (
<div className="main_container">
{message}
</div>
);
}
}
解释
在组件dod-mount函数中,您可以通过其id获取小部件,并从中获取message
属性,然后将此消息设置为state。