简体   繁体   English

在类组件中导入功能组件

[英]Importing functional Component in class component

I have created a hook based functional component and trying to import that functional component in the class-based component, but I'm getting this below error我创建了一个基于钩子的功能组件并尝试在基于类的组件中导入该功能组件,但我收到以下错误

在此处输入图片说明

functional component code :-功能组件代码:-

import React, { useState } from "react";

const SearchBar = () => {
  const [searchBtn, setSearchBtn] = useState(false);

  return (
    <div className="search-bar">
      <input className="search-text" type="text" placeholder="Search..." />
      {searchBtn ? (
        <button
          title="Back"
          onClick={() => setSearchBtn(false)}
          className="search-btn "
        />
      ) : (
        <button
          title="Search"
          onClick={() => setSearchBtn(true)}
          className="search-btn "
        />
      )}
    </div>
  );
};

export default SearchBar;

I am using the react-dom version: 16.8.6我正在使用 react-dom 版本:16.8.6

Rules of Hooks钩子规则

Only Call Hooks at the Top Level只在顶层调用钩子

Don't call Hooks inside loops, conditions, or nested functions.不要在循环、条件或嵌套函数中调用 Hook。 Instead, always use Hooks at the top level of your React function.相反,始终在 React 函数的顶层使用 Hook。 By following this rule, you ensure that Hooks are called in the same order each time a component renders.通过遵循此规则,您可以确保每次渲染组件时以相同的顺序调用 Hook。 That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.这就是允许 React 在多个useStateuseEffect调用之间正确保留 Hooks 状态的useEffect (If you're curious, we'll explain this in depth below.) (如果你很好奇,我们将在下面深入解释这一点。)

for better understanding check this https://reactjs.org/docs/hooks-rules.html为了更好地理解,请检查这个https://reactjs.org/docs/hooks-rules.html

There is nothing wrong with your component.您的组件没有任何问题。 The most common case for your error is using some third party component that expects a function to render something (and calls it as a function) rather than a react component:最常见的错误情况是使用一些第三方组件,该组件期望函数渲染某些内容(并将其称为函数)而不是反应组件:

// how you expect it to be called
<SearchBar />
...
// how it is actually called
{SearchBar()}

if that's the case, change it from someProp={SearchBar} to someProp={() => <SearchBar />}如果是这种情况,请将其从someProp={SearchBar}更改为someProp={() => <SearchBar />}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM