首页 > 解决方案 > 如何将 Preact 网站嵌入到现有网站中?

问题描述

我创建了一个 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

解决方案


现有应用程序 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/


推荐阅读