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

Categories

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

reactjs - React function displayBanner = () => {

I am currently working on a project and trying to attempt 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 it checks if the !bannerHdr && !bannerMsg (if no text the variables are undefined) then change className = 'hide' the banner else 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?

question from:https://stackoverflow.com/questions/65602675/react-function-displaybanner

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

1 Reply

0 votes
by (71.8m points)

The logic should be a part of the style prop:

<HeaderWrapper style={{ visibility: props.isBannerVisible ? 'hidden' : 'none' }}>

If you still want to have a function you should return an object instead of a string, so it will match the style prop:

function hideBanner(isBannerVisible) {
  return { visiblity: isBannerVisible ? "hidden" : "none" };
}

<HeaderWrapper style={{ ...hideBanner(props.isBannerVisible) }} />;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...