簡體   English   中英

如何將“歷史”object 傳遞給 stencil.js 組件<stencil-router></stencil-router>

[英]How to pass 'history' object to stencil.js component <stencil-router>

我需要在組件( <app-nav> )中使用歷史 Object ,該組件被呈現為<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)

package.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"

知道為什么我總是不確定嗎? 先感謝您

編輯:對不起,我應該更仔細地查看您的代碼,您確實有 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 下查看)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM