Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

reactjs - React function displayBanner compile issue

I am currently working on a project and trying to hide a banner by changing the state of a className like the following:

<div?className={visbilityBanner}>

I have a Hide Banner button like the following:

 <button
????type="button"
????className="btn?btn-secondary?btn-sm"
????size="small"
????style={hideButtonsStyle}
????onClick={(e)?=>?displayBanner(e)}
????>
???????Hide?Banner
????</button>

My train of thought is the solution needs a function called displayBanner. In the code below I check if the !bannerHdr && !bannerMsg (if no text the variables are undefined) then change className = 'hide' else change to className = 'show'

const?displayBanner?=?()?=>?{
????const?[visbilityBanner,?setVisbilityBanner]?=?useState('show');

????if?(!bannerHdr?&&?!bannerMsg)?{??????????????????
??????setVisbilityBanner('hide');??????
????????console.log(visbilityBanner);?????
????????return?visbilityBanner;
????}?
????setVisbilityBanner('show');?????
??????console.log(visbilityBanner);
??????return?visbilityBanner;
????};

However, I am getting a compile error:

Failed to compile

Failed to compile
./src/components/Banners.js
  Line 220:  React Hook "useState" is called in function "displayBanner" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks
  Line 249:  'visbilityBanner' is not defined                                                                                                         no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.

Can anyone assist in explaining what I?am missing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use React Hooks in Top level of a Component not inside a function or if block, change your code to this and you're good to go:

const [visbilityBanner, setVisbilityBanner] = useState("show");

const displayBanner = () => {
  if (!bannerHdr && !bannerMsg) {
    setVisbilityBanner("hide");
    console.log(visbilityBanner);
    return visbilityBanner;
  }
  setVisbilityBanner("show");
  console.log(visbilityBanner);
  return visbilityBanner;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...