简体   繁体   English

使用 React Hooks 隐藏点击按钮

[英]Hide button on click using React Hooks

I currently have a button that when clicked on shows another component, however I want this specific button to also be hidden when it's clicked on.我目前有一个按钮,单击时会显示另一个组件,但是我希望在单击此特定按钮时也将其隐藏。 Any idea?任何想法? Thanks.谢谢。

const [showSecondFields, setShowSecondFields] = React.useState(false);
const onClick = () => setShowSecondFields(true);

const SecondFields = () => (
<div>
<p>Second Component</p>
</div>
);

<button type="button" className="button--secondary" onClick={onClick}>
 Show Component
</button>
{showSecondFields ? <SecondFields /> : null}

If the components are siblings, you can use a ternary to switch between them:如果组件是同级组件,则可以使用三元组在它们之间切换:

 const SecondFields = () => ( <div> <p>Second Component</p> </div> ); const Demo = () => { const [showSecondFields, setShowSecondFields] = React.useState(false); const onClick = () => setShowSecondFields(true); return showSecondFields? <SecondFields />: ( <button type="button" className="button--secondary" onClick={onClick}> Show Component </button> ); } ReactDOM.render( <Demo />, root )
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

You can put both in one ternary condition你可以把两者都放在一个三元条件下

This way you can return one component if the condition is true and another component if the condition is false这样,如果条件为真,您可以返回一个组件,如果条件为假,则返回另一个组件

Do it this way这样做

{!showSecondFields ?   //if condition true
   <button type="button" className="button--secondary" onClick={onClick}>
       Show Component
   </button>
       :  <SecondFields />  //if condition false
}

You could simply do something along the lines of this:您可以简单地按照以下方式做一些事情:

{!showSecondFields && <button className="button--secondary" onClick={onClick}>
 Show Component
</button>}

{showSecondFields && <SecondFields /> }

The first ternary operator shows the button if the condition is false, the second operator shows the fields if the condition is true.如果条件为假,第一个三元运算符显示按钮,如果条件为真,第二个运算符显示字段。

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

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