簡體   English   中英

如何正確編寫React組件的包裝器?

[英]How to properly write a wrapper for a React component?

現在大部分導航都已到位,您應該這樣做,以便PetList中顯示不同的寵物。 為此,請修改App組件中的/ route,以便指定render屬性,而不是指定component屬性。 該屬性被賦予一個回調函數,該函數接收一組道具,並返回帶有這些道具的<PetList>元素以及原始pet道具。

提示:嘗試將此函數聲明為Apprender()函數內的局部變量,然后將該函數值作為prop傳遞。 這有助於提高可讀性。

一旦這樣做,你應該能夠在訪問/ route時看到寵物卡列表。

這是主要問題,我已經解決了如何在沒有包裝器的情況下進行路由。 問題是,一旦我嘗試將其寫入局部變量,我就會迷失方向。 我有幾個問題包括:

  • 我在哪里放置這個局部變量? 它放在render函數中的return語句之前是否正確?
  • 上面的鏈接顯示了如何執行此操作; 我不知道如何應用這種情況
  • 我真的不明白...而且...rest的目的是什么...單獨以及...rest
render() {
  return (
    <div>
      <header className="jumbotron jumbotron-fluid py-4">
        <div className="container">
          <h1><Link to='/'>Adopt a Pet</Link></h1>
        </div>
      </header>

      <main className="container">
        <div className="row">
          <div className="col-3">
            <AboutNav />
          </div>
          <div className="col-9">
            <Switch>
              <Route exact path='/' render={() => 
                <PetList pets={this.state.pets} />
              } />
              <Route exact path='/about' component={AboutPage} />
              <Route exact path='/resources' component={ResourcesPage} />
              <Redirect to='/' />
            </Switch>
          </div>
        </div>
      </main>

      <footer className="container">
        <small>Images from <a href="http://www.seattlehumane.org/adoption/dogs">Seattle Humane Society</a></small>
      </footer>
    </div>
  );
}

我在哪里放置這個局部變量? 它放在render函數中的return語句之前是否正確?

是。 你有這個:

render() {
  return (
    // ...
    <Route exact path='/' render={() => 
      <PetList pets={this.state.pets} />
    } />
    // ...
  );
}

文本告訴你做這樣的事情:

render() {
  const renderPetList = () => <PetList pets={this.state.pets} />;

  return (
    // ...
    <Route exact path='/' render={renderPetList} />
    // ...
  );
}

我真的不明白...而且...rest的目的是什么...單獨以及...rest

我不知道這是什么參考,但我猜你已經在對象解構的背景下看到了它。

這是一個人為的例子,但是假設你想為<button>創建一個包裝器,它帶有一些你直接傳遞給<button>的道具和一個你不會傳遞的道具(讓我們說“ mySize ”),因為你想先用它做別的事。 你可以這樣做:

const MyButton = ({ mySize, childen, disabled, tabIndex, onClick, children }) => {
  const className = mySize === 'big' ? 'big-button' : 'normal-button';

  return (
    <button className={className} disabled={disabled} tabIndex={tabIndex} onClick={onClick}>
      {children}
    </button>
  );
};

但這真的很冗長。 相反,重復全部,我們要傳遞給道具的名稱<button> ,我們可以使用... (以下簡稱“傳播經營者”),以挑選出一定的道具擺在與變量,我們將其余的做(ergo ...rest ,盡管你可以隨意調用它)進入一個物體,使它更簡潔:

const MyButton = ({ mySize, ...restProps }) => {
  const className = mySize === 'big' ? 'big-button' : 'normal-button';

  return (
    <button className={className} {...restProps}>
      {children}
    </button>
  );
};

暫無
暫無

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

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