通过高阶组件反应搜索过滤器(挂钩)不起作用
React Search filter (hooks) through a High Order Component not working
我尝试让我的 React 搜索框过滤器正常工作。
看看 this sandbox 我目前有什么。
我有一个 HOC withSection.js
,我在其中(现在)只向我的组件添加了一个 <section>
标签:
const withSection = Component => props => (
<section>
<Component {...props} />
</section>
)
然后在父组件中,我将我的 SearchBox 组件包装到这个 HOC 中并渲染它:
const SectionSearchBox = withSection(SearchBox);
<SectionSearchBox search={search} setSearch={setSearch} />
不知何故,一旦我将我的 SearchBox 包装到这个 HOC 中,它就破坏了功能?
这里有什么问题吗?
您需要在其父组件范围之外声明SectionSearchBox
。在 codesandbox 示例中,它看起来像:
import withSection from "./hoc/withSection";
import SearchBox from "./SearchBox";
const SectionSearchBox = withSection(SearchBox);
function ArticlePage() {
...
};
否则,该组件的每个实例都将与其父组件的每个新渲染一起重新创建(即当搜索词更改时)。这导致搜索框在每次击键时都显得没有焦点,因为一个新的输入元素被放置在它的位置上,其中包含之前呈现的值。
我尝试让我的 React 搜索框过滤器正常工作。
看看 this sandbox 我目前有什么。
我有一个 HOC withSection.js
,我在其中(现在)只向我的组件添加了一个 <section>
标签:
const withSection = Component => props => (
<section>
<Component {...props} />
</section>
)
然后在父组件中,我将我的 SearchBox 组件包装到这个 HOC 中并渲染它:
const SectionSearchBox = withSection(SearchBox);
<SectionSearchBox search={search} setSearch={setSearch} />
不知何故,一旦我将我的 SearchBox 包装到这个 HOC 中,它就破坏了功能?
这里有什么问题吗?
您需要在其父组件范围之外声明SectionSearchBox
。在 codesandbox 示例中,它看起来像:
import withSection from "./hoc/withSection";
import SearchBox from "./SearchBox";
const SectionSearchBox = withSection(SearchBox);
function ArticlePage() {
...
};
否则,该组件的每个实例都将与其父组件的每个新渲染一起重新创建(即当搜索词更改时)。这导致搜索框在每次击键时都显得没有焦点,因为一个新的输入元素被放置在它的位置上,其中包含之前呈现的值。