简体   繁体   English

在按钮单击中显示组件(使用挂钩)

[英]display a component in button click (using hooks)

I'm trying to display a component in button click, What do I need to change in the syntax ?我正在尝试在button单击中显示component ,我需要更改syntax什么?
Anyone understand where the mistake is?任何人都明白错误在哪里? The functions works but not as I need to, I have progressed since the previous question here display a different component with each button click这些功能有效,但不是我需要的,自从上一个问题在这里显示每个按钮单击时显示不同的组件以来,我已经取得了进展

I really want to understand the right and the simple method好想明白正确简单的方法

Thanks!谢谢!

App.js应用程序.js

import React, {useState} from 'react';
import './App.css';
import Addroom from './components/Addroom.js'
import HomePage from './components/HomePage.js'

function App() {

  const [flag, setFlag] = useState(false);



  return (
    <div className="App">
     
     <h1>My Smart House</h1>


      <button className="button1" onClick={()=>setFlag(!flag)}>Change Flag</button>
      {flag.toString()}

      <Addroom a={(!flag)}/>
      <HomePage h={(flag)}/>

</div>

  )
}
export default App;

HomePage.js主页.js

import React from 'react'

export default function HomePage(props) {
    return (
        <div>
           <h2> HomePage {props.h}</h2>
        </div>
    )
}


Addroom.js Addroom.js


import React from 'react';


export default function Addroom(props) {
    return (
        <div>
           <h2> Addroom {props.a}</h2>
        </div>
    )
}

With conditional operator condition? exprIfTrue: exprIfFalse使用条件运算符condition? exprIfTrue: exprIfFalse condition? exprIfTrue: exprIfFalse

   {flag ? <Addroom /> : <HomePage /> }

If you don't need to use the flag inside components, skip passing as props如果您不需要在组件内使用flag ,请跳过作为道具传递

look at this sample sample看看这个样本

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

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