gpt4 book ai didi

javascript - 如何使 react 路由器链接加载页面像 anchor 标签?

转载 作者:行者123 更新时间:2023-11-30 06:12:50 24 4
gpt4 key购买 nike

在我的一个组件上,我有一个外部小部件,它需要一个脚本标签和一个特殊的 div 元素。页面加载后,脚本会在 div 中插入一个 iframe。

我遇到的问题是,该小部件仅在页面像普通 http 页面一样加载时才起作用。当我使用 anchor 标记时,这个小部件可以工作,但是使用链接时,它不会工作,因为没有页面加载。

列表组件----链接---->属性组件

如何使用 Link 实现相同的行为?

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>

列表.js

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

属性.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>

最佳答案

这是 React Portals 的一个基本示例。

Index.html

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

我的组件

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;

您现在可以使用 MyWidget 组件。希望这可以帮助。谢谢!

关于javascript - 如何使 react 路由器链接加载页面像 anchor 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57892908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com