【问题标题】:display a component in button click (using hooks)在按钮单击中显示组件(使用挂钩)
【发布时间】:2020-11-09 04:00:31
【问题描述】:

我正在尝试在button 点击中显示component,我需要在syntax 中进行哪些更改?
任何人都明白错误在哪里? 这些功能有效,但不是我需要的, 自从上一个问题在这里display a different component with each button click

好想明白正确简单的方法

谢谢!

App.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;

主页.js

import React from 'react'

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


Addroom.js


import React from 'react';


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

【问题讨论】:

  • The functions works but not as I need to 对于不熟悉您的项目的任何人来说,这不足以了解发生了什么问题。请更详细地描述问题所在。
  • 我想在每个按钮点击一个布尔值时显示一个不同的组件,但我没有在钩子中正确使用..

标签: javascript reactjs components react-hooks react-functional-component


【解决方案1】:

带条件运算符condition ? exprIfTrue : exprIfFalse

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

如果您不需要在组件内部使用flag,请跳过作为道具传递

看看这个样本 sample

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 2019-05-17
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2018-05-04
    • 1970-01-01
    相关资源
    最近更新 更多