是否有更好的方法将多个道具传递给n个孩子

kev*_*vin 4 javascript reactjs

目前正在工作一个小组项目,我一直在研究小组编写的代码,我很好奇是否有更好的方法可以将prop传递给n个子组件,从而改变顶级App组件的状态。

目前,我们有这样的事情:

return (
  <div>
    <header className="navBar">
      // NavBar is an example for the question
      <NavBar
        showSplash={this.state.showSplash}
        displayAllSearchResults={this.displayAllSearchResults}
        searchBarDisplay={this.state.showCard}
        updateResults={this.updateResults}
        selectResult={this.selectResult}
        searchResults={this.state.searchResults}
        showSuggestions={this.state.showSuggestions}
      />
    </header>
    <section className="App">
      <article className="mainContent">{card}</article>
    </section>
    <div className="appBackground" />
  </div>
);

Run Code Online (Sandbox Code Playgroud)

所有这些方法(可能有太多)都被传递到NavBar本身由一个SearchBar组件组成的组件中,该组件也需要传递巨大的块,以便从一开始就改变状态App。这感觉不对,是有一个解决方案或更好的方法来通过所有这些道具了吗?

Abd*_*MEL 7

您可以spread像这样使用运算符:

<NavBar  {...this.state} />
Run Code Online (Sandbox Code Playgroud)

它将状态属性作为道具传递给导航栏。

在您的Navbar组件中,您可以从中获取showSplashstate 的值props.showSplash

如果要将数据传递到Navbar的子组件中,可以执行以下操作:

<ChildComponent {...props} /> // if Navbar is a functional component

<ChildComponent {...this.props} /> // if Navbar is a stateful component
Run Code Online (Sandbox Code Playgroud)

参考:

传播对象文字

这是用于说明的样本stackblitz