简体   繁体   English

如何在组件的JSX中嵌入脚本?

[英]How to embed a script in JSX in a component?

I have a script that loads an iframe that i have to embed on a particular route 我有一个脚本可以加载必须嵌入特定路由的iframe

My application is a universally rendered React app, and I included the script in my JSX code in the component registered to my route. 我的应用程序是一个通用渲染的React应用程序,并且我将该脚本包含在我的JSX代码中,该脚本已注册到我的路线中。

The iframe loads when I refresh the page on the route, but when I go from home -> other route, it wont load. 当刷新路线上的页面时,iframe就会加载,但是当我从首页->其他路线上去时,它不会加载。

I've tried different workarounds using componentWillMount and componentDidMount , but to no avail. 我尝试了使用componentWillMountcomponentDidMount其他变通办法,但无济于事。 Is there a way to force it to load when I visit the route from another route? 当我从其他路线访问路线时,是否有一种方法可以强制它加载?

EDIT: i've checked and the script, is always there, but does not execute when not using server-side rendering 编辑:我已经检查过并且脚本始终存在,但是在不使用服务器端渲染时不执行

someone else had the same problem here and there was no sufficient solution short of including it at the root component of the app, which is overkill. 有人在这里遇到了同样的问题,没有足够的解决方案,只能在应用程序的根组件中包含它,这是过大的。 so i have no idea what the solution is :( 所以我不知道解决方案是什么:(

class Component extends React.Component {

constructor(props) {
    super(props)
}

render() {
    return (
        <div className='container'>
            <script id="twine-script" src="//apps.twinesocial.com/embed?app=WCD&showNav=yes"></script>
        </div>
}

You should be able to inject a script on componentWillMount into the document head. 您应该能够将componentWillMount上的脚本注入到文档头中。 You can argue that this isn't the most React way, but I think in this particular case it makes sense. 您可以说这不是最React的方式,但是我认为在这种特殊情况下是有道理的。

const MyRouteComponent = React.createClass({

    componentWillMount() {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.onload = () => {
            this.setState({
                isLoaded: true
            });
            console.log(TwineSDK); // TwineSDK should be defined now
        };
        script.src = '//apps.twinesocial.com/embed?app=WCD&showNav=yes';
        document.head.appendChild(script);
    },

    getInitialState() {
        return {
            isLoaded: false
        }
    },

    render() {
        return (
            <div>
            {
                this.state.isLoaded ? <div>Loaded!</div> : <div>Loading...</div>
            }
            </div>
        );
    }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM