简体   繁体   English

如何使响应路由器链接加载页面像锚标签?

[英]How to make react router Link load page like anchor tag?

on one of my components I have an external widget which requires a script tag and a special div element. 在我的一个组件上,我有一个外部小部件,它需要一个脚本标签和一个特殊的div元素。 Once the page loads the script inserts an iframe inside the div. 页面加载后,脚本会在div内插入一个iframe。

The issue I am having is that the widget only works when the page is loaded like a normal http page. 我遇到的问题是,该窗口小部件仅在像正常的http页面一样加载页面时才起作用。 This widget works when I use anchor tags however with Link it doesn't as there is no page load. 当我使用锚标记时,此小部件可以工作,但是对于Link,则不起作用,因为没有页面加载。

List component ----Link----> Property component 列表组件---- Link ---->属性组件

How can I achieve the same behavior but with Link? 如何通过Link实现相同的行为?

App.js App.js

    <Switch> 
        <Route path="/" exact component={Home} />
        <Route path="/list" exact component={List} />
        <Route path="/property/:id/:sleeps/:start/:end" exact component={Property} />
        <Route component={Error} />
    </Switch>

List.js List.js

<Link to={`/property/${property.id}/${property.sleeps}/${property.start}/${property.end}`}>
    <img src={property.image} alt={property.name}/>
</Link>

Property.js Property.js

componentDidMount = () => {
    //function inserts script to body
    this.loadScript('https://widgetSite.co.uk/components/embed.js');
}

//inside render
<div
    data-calendar-key="widget key"
    data-calendar-property-id={this.propID}
    id="calendar-js">
    Your widget will appear here.
</div>

Here is a basic example of React Portals. 这是React Portal的基本示例。

Index.html

<body>
  <div id="root"></div>
  <div id="my-widget"></div>
</body>

MyWidget Component MyWidget组件

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

const Widget = document.getElementById('my-widget');

class MyWidget extends Component {
  state = { openWidget: false };

 //functions to open close widget

  render() {
    return ReactDOM.createPortal(this.renderWidget(), Widget);
  }

  renderWidget() { /*add your widget elements*/ }
}

export default MyWidget;

You can now use the MyWidget component. 现在,您可以使用MyWidget组件。 Hope this helps. 希望这可以帮助。 Thanks! 谢谢!

Try to implement something like this How to force a script reload and re-execute? 尝试实现类似这样的方法如何强制脚本重新加载并重新执行? in your loadScript function so your script will be force to re-load, re-execute and grab the right data-* every time componentDidMount is trigger. 在loadScript函数中,以便每次触发componentDidMount时,脚本将被强制重新加载,重新执行并获取正确的数据*。 I hope this help 希望有帮助

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

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