如何使用React Hooks来获取按钮单击上的数据

时间:2020-10-10 05:51:16

标签: react-hooks

我想在单击Button时显示Child组件,但是在这里,我是在页面加载时获取数据,我需要编写类似Button Clicked时的条件,然后只有Child组件显示才能显示,否则应使用默认文本显示在那里。

const DetailsCard = () => {

    const [employee, setemployee] = useState([])
    const [data, setData] = useState()

    useEffect(() => {
        fetch("http://localhost:3000/users").then(res => res.json()).then((result) => {
            setemployee(result);
        }, [])
    })

    const handleChange = () => {

        setData(true);

    }

    return (
        <div>
            <h1>LordShiva</h1>
            <div className="container">
                <div className="row">
                    <div className="col">
                        <div className="card">
                            <div className="card-header bg-primary text-white">
                                <p className="h4">Birthday APP</p>
                                <button className="btn btn-red true1 " onClick={handleChange} >HappyBirthday</button>
                            </div>
                            <div className="card-body">
                                <TableCard data={employee} />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default DetailsCard;

1 个答案:

答案 0 :(得分:1)

const DetailsCard = () => {
  const [employee, setemployee] = useState([]);
  const [showChild, toggleShowChild] = useState(false);

  useEffect(() => {
    fetch("http://localhost:3000/users")
      .then((res) => res.json())
      .then((result) => {
        setemployee(result);
      }, []);
  });

  const handleChange = () => {
    toggleShowChild(!showChild);
  };

  return (
    <div>
      <h1>LordShiva</h1>
      <div className="container">
        <div className="row">
          <div className="col">
            <div className="card">
              <div className="card-header bg-primary text-white">
                <p className="h4">Birthday APP</p>
                <button className="btn btn-red true1 " onClick={handleChange}>
                  HappyBirthday
                </button>
              </div>

              {/* Only show child when `showChild` is true. */}
              {showChild && (
                <div className="card-body">
                  <TableCard data={employee} />
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default DetailsCard;

Codesandbox