首页 > 解决方案 > 如何将“历史”对象传递给 stencil.js 组件

问题描述

我需要在 Component( <app-nav>) 中使用历史对象,该对象被呈现为<app-root>

但是,根据我遵循的一些教程,我完全无法将History(Appnav) 注入组件。我总是得到一个未定义的日志。

结构如下:

应用程序-root.tsx

export class AppRoot {

  render() {
    return (
      <div>
        <header>
          <h1>Stencil App Starter</h1>
        </header>

        <main>
          <stencil-router>
            <stencil-route-switch scrollTopOffset={0}>
              <stencil-route url="/" component="app-home" exact={true} />
              <stencil-route url="/profile/:name" component="app-profile" />
            </stencil-route-switch>
          </stencil-router>
          
          <app-nav></app-nav>


        </main>
      </div>
    );
  }
}

应用导航.tsx

import { Component, h, Prop } from '@stencil/core';
import { RouterHistory, injectHistory } from '@stencil/router';

@Component({
  tag: 'app-nav',
  shadow: false,
})
export class Appnav {
  @Prop() history: RouterHistory
  render() {
    return (
      <div class="app-nav">
        <p>
         Mi navegacion 3
        </p>
        <button onClick={()=> this.draw()}>log history</button>
      </div>
    )
  }

  draw(){
      console.log(this.history);      
  }
}

injectHistory(Appnav)

包.json

"@stencil/core": "^2.0.0",
"@stencil/router": "^1.0.1",
"@stencil/store": "^1.4.1",
"@stencil/utils": "0.0.5",
"workbox-build": "^4.3.1"

知道为什么我总是不确定吗?先感谢您

标签: javascripttypescriptnavigationstenciljs

解决方案


编辑: 对不起,我应该更仔细地查看您的代码,您确实有 RouterHistory - 那么它不起作用的原因可能是您的组件(app-nav)不在“模板路由器”(组件需要是通过 stencil-route组件道具引用 - 也可能与routeRender()道具一起使用?)

(在上面添加编辑之前的原始回复)

对于 v1 路由器,您可以将RouterHistory作为 prop 传递给组件(组件需要包含在 stencil-route 中,并且您不需要显式传递它 - stencil 在幕后为您完成)

import { RouterHistory } from '@stencil/router';
@Prop() history: RouterHistory;

...

//then use it to manipulate history (say bound this function to button click)
goBackHistory() {
  this.history.goBack();
}

链接到 Stencil 文档(在 Navigating Programtically 下查看)


推荐阅读