简体   繁体   中英

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

Rules of Hooks

Only Call Hooks at the Top Level

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you're curious, we'll explain this in depth below.)

for better understanding check this 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 />}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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