首页 > 解决方案 > 在 React.js 的函数中尝试钩子和状态

问题描述

这段代码在语法上是否正确?我想要达到的效果是在单击按钮后出现文本......

import React, { useState } from 'react';
import './App.css';

function Example(){
  const [state, setState] = useState({shows: false});

  return(
    <div>{state.shows && <p>hi</p>}
      <button onClick={() => setState({shows: true})}>
        Click me
      </button>
    </div>
  )
}

export default Example;

标签: htmlreactjs

解决方案


是的,但你不需要使用对象

function Example(){
 const [state, setState] = useState(false);

 return(
  <div>{state && <p>hi</p>}
   <button onClick={() => setState(true)}>
     Click me
   </button>
  </div>
 )
}

推荐阅读