【问题标题】:How do I embed a Preact website into existing website?如何将 Preact 网站嵌入到现有网站中?
【发布时间】:2018-10-22 16:10:16
【问题描述】:

我创建了一个 Preact 网站:https://alwaysselector-2d06f.firebaseapp.com/,另一个网站允许我在他们的“contentDiv”中上传内容。

<div id="contentDiv">
 //what should I put here?
</div>

我的问题是我不知道在 div 中放什么。我不想使用 iFrame,因为在某些情况下我的外部网站高度可能会有所不同。因此,

<iframe src='https://alwaysselector-2d06f.firebaseapp.com/' /> 

不会工作。从我的外部网站获取所有 html 以在 contentDiv 中加载的最简单方法是什么?

【问题讨论】:

    标签: preact


    【解决方案1】:

    现有的应用程序 HTML

    <div id="someOtherApp">
       <h1>
         Some other app
       </h1>
       <div id="addYourPreactApp">
           <h1>Add Preact app hook here</h1>
           <div id="preactAppRoot"> 
           </div>
       </div>
    </div>
    

    现在您可以将您的 preact 应用程序挂接到 html 元素 (div#preactAppRoot)。

    /** @jsx h */
    const { h, render, Component } = preact;    // normally this would be an import statement.
    
    class Clock extends Component {
        constructor() {
            super();
            // set initial time:
            this.state.time = Date.now();
        }
    
        componentDidMount() {
            // update time every second
            this.timer = setInterval(() => {
                this.setState({ time: Date.now() });
            }, 1000);
        }
    
        componentWillUnmount() {
            // stop when not renderable
            clearInterval(this.timer);
        }
    
        render(props, state) {
            let time = new Date(state.time).toLocaleTimeString();
            return <span>{ time }</span>;
        }
    }
    
    // render an instance of Clock into <body>:
    render(<Clock />, document.getElementById("preactAppRoot"));
    

    可以在 jsfiddle 上找到工作示例 - https://jsfiddle.net/cte27dhw/

    【讨论】:

    • 感谢 front_end_dev,几乎就在那里,但假设 preact 应用程序托管在其他地方,我无法在其他现有应用程序中添加整个 preact 应用程序(想象它有 100,000 行而且太大)。我如何导入 preact 应用程序,然后将 preact 应用程序加载到现有的 html 应用程序。我是否使用脚本标签来导入我的 preact 应用程序,然后在我的 preact 应用程序中导入类似“window.parent.document.getElementById”的内容?
    • @Will - 我希望你正在生成 preact 应用程序的生产包。您只需将该脚本添加到要添加您的 preact 应用程序的第三方 html 文件中。请查看更新的 jsfiddle - jsfiddle.net/uL897c1t/1
    • 感谢@front_end_dev ...我将如何加载该js? div id="someOtherApp">

      Some other app

      Add Preact app hook here

      //我该怎么做放在这里,像这个脚本?
  • @Will 你不必在这里放任何东西。使用 render 函数完成附加 preact 代码的挂钩。看这个 [Without_Uglify_Fiddle](jsfiddle.net/cte27dhw) 最后一行是render(&lt;Clock /&gt;, document.getElementById("preactAppRoot"));。这里 preact 代码附加在 id 为 preactAppRoot 的元素上。第 3 方 html 只需要添加一个 div 元素 (#preactAppRoot) 并将附加代码捆绑到该元素中。 Fiddle_With_Uglify_That_is_Your_Bundle_Also 。如果您仍然想知道它是如何工作的,那么我可以创建一个 github gist 并与您分享。
  • 猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2021-09-03
    相关资源
    最近更新 更多