如何在 React 中构造 js 对象
How to construct js object in React
我在 React 和 Advertisement 方面遇到了一些问题。
想使用 'Coupang' 广告,但他们只支持脚本库。
我可以将它添加到 public 目录中的 'index.html',但无法自定义位置。
这是代码,
<script src="https://ads-partners.coupang.com/g.js"></script>
<script>
new PartnersCoupang.G({"id":23232,"subId":null});
</script>
动态广告。
如何将其添加到 React 功能组件中??
MB 这会有所帮助。
useScript 将帮助您动态地将脚本添加到您的代码中。
你自定义挂钩(只需创建 PartnersCoupang
);
const usePartnersCoupang = () => {
const const [loaded, error] = useScript('https://ads-partners.coupang.com/g.js');
React.useEffect(() => {
if (loaded) {
new PartnersCoupang.G({"id":23232,"subId":null});
}
}, [loaded]);
React.useEffect(() => {
if (error) {
console.error('PartnersCoupang Failed.');
}
}, [error]);
}
实际上,您应该通过以下命令从 create-react-app
项目中 eject
:
$ yarn eject
或:
$ npm run eject
然后你可以看到一个名为config
的文件夹,在这个文件夹中你可以看到你项目的所有配置,特别是你的Webpack配置,然后你应该将你的外部库添加到webpack中作为external
Webpack配置关键:
// webpack.config.js
...
module.exports = {
...
externals: {
PartnersCoupang: '[path-to]/g.js',
},
...
};
然后在您的组件中轻松导入它:
import React, { Component } from 'react';
import PartnersCoupang from 'PartnersCoupang';
class YourComponent extends Component {
componentDidMount() {
new PartnersCoupang.G({"id":23232,"subId":null});
}
}
我在 React 和 Advertisement 方面遇到了一些问题。 想使用 'Coupang' 广告,但他们只支持脚本库。 我可以将它添加到 public 目录中的 'index.html',但无法自定义位置。
这是代码,
<script src="https://ads-partners.coupang.com/g.js"></script>
<script>
new PartnersCoupang.G({"id":23232,"subId":null});
</script>
动态广告。 如何将其添加到 React 功能组件中??
MB 这会有所帮助。
useScript 将帮助您动态地将脚本添加到您的代码中。
你自定义挂钩(只需创建 PartnersCoupang
);
const usePartnersCoupang = () => {
const const [loaded, error] = useScript('https://ads-partners.coupang.com/g.js');
React.useEffect(() => {
if (loaded) {
new PartnersCoupang.G({"id":23232,"subId":null});
}
}, [loaded]);
React.useEffect(() => {
if (error) {
console.error('PartnersCoupang Failed.');
}
}, [error]);
}
实际上,您应该通过以下命令从 create-react-app
项目中 eject
:
$ yarn eject
或:
$ npm run eject
然后你可以看到一个名为config
的文件夹,在这个文件夹中你可以看到你项目的所有配置,特别是你的Webpack配置,然后你应该将你的外部库添加到webpack中作为external
Webpack配置关键:
// webpack.config.js
...
module.exports = {
...
externals: {
PartnersCoupang: '[path-to]/g.js',
},
...
};
然后在您的组件中轻松导入它:
import React, { Component } from 'react';
import PartnersCoupang from 'PartnersCoupang';
class YourComponent extends Component {
componentDidMount() {
new PartnersCoupang.G({"id":23232,"subId":null});
}
}