Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

reactjs - how do control the state for multiple component with one function

I have one simple app that include 3 identical button and when I click the button, onClick event should trigger to display one span. for now, I have use one one state to control span show or not and once I click any one of button all span show. How can I implement the code, so when I click the button, only the correspond span display

import "./styles.css";
import React, { useState } from "react";

const Popup = (props) => {
  return <span {...props}>xxx</span>;
};

export default function App() {
  const [isOpen, setIsOpen] = useState(true);
  const handleOnClick = () => {
    setIsOpen(!isOpen);
  };
  return (
    <div className="App">
      <button onClick={handleOnClick}> Show popup1</button>
      <Popup hidden={isOpen} />
      <button onClick={handleOnClick}> Show popup2</button>
      <Popup hidden={isOpen} />
      <button onClick={handleOnClick}> Show popup3</button>
      <Popup hidden={isOpen} />
    </div>
  );
}

codesandbox: https://codesandbox.io/s/cocky-fermi-je8lr?file=/src/App.tsx

question from:https://stackoverflow.com/questions/66068017/how-do-control-the-state-for-multiple-component-with-one-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should rethink how the components are used. Since there is a repeating logic and interface, it should be separated to a different component.

const Popup = (props) => {
  return <span {...props}>xxx</span>;
};

interface Props {
  buttonText: string
  popupProps?: any
}

const PopupFC: React.FC<Props> = (props) => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(!isOpen)}>{props.buttonText}</button>
      <Popup hidden={isOpen} {...props.popupProps} />
    </>
  )
}
export default function App() {
  const [isOpen, setIsOpen] = useState(true);
  const handleOnClick = () => {
    setIsOpen(!isOpen);
  };
  return (
    <div className="App">
      <PopupFC buttonText="Show popup1" />
      <PopupFC buttonText="Show popup2" />
      <PopupFC buttonText="Show popup3" />
    </div>
  );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...