How can I pass state from page to component and back to page?

假装没事ソ 提交于 2021-02-11 12:46:37

问题


Is there a way without using Redux with which I can from my home.js page (I'm using hooks not classes) set/use a state, pass it to my component MyComponent.js and once a div is clicked inside this component update the state (so for the home.js page as well)?

In home.js I have something like:

export default function Page({ session, items }) {

  const [selectedTab, setSelectedTab] = useState('main')
  const handleSelect = (e) => {
    setSelectedTab(e);
  }

  ... // then I return some react-bootstrap tabs, where Tab.Container is like:

   <Tab.Container id="tabs-home" activeKey={selectedTab} onSelect={(e) => handleSelect(e)}>

   ...
}

In MyComponent.js I tried:

export default function MyComponent(props) {

  const [selectedTab, setSelectedTab] = useState()

  const handleClick = () => {
    setSelectedTab("second");
  }

  ... // and I return something like:

  <div onClick={() => handleClick()} style={{cursor: 'pointer'}}>blahblah</div>

So basically when clicking on the item inside the component I need to change selected tab in the page. I'll then need to pass props as well from the component back to the page, but once I understand how I can pass state I guess is the same process again


回答1:


Here is a quick snippet illustrating the concept of holding state in the parent and passing control to children.

const App = () => {
  const [state, setState] = React.useState('main');

  const handleState = (e) => {
    console.clear();
    console.log(e.target);
    setState(e.target.id);
  }

  return (
    <div>
      <Tab id="main" state={state} handleState={handleState} />
      <Tab id="second" state={state} handleState={handleState} />
      <Tab id="third" state={state} handleState={handleState} />
    </div>
  )
}

const Tab = ({ id, state, handleState }) => {

  return (
    <div id={id} className={state === id && 'active'} onClick={handleState}>
      {id}
    </div>
  );
}


ReactDOM.render(
  <App />,
  document.getElementById("root")
);
.active {
  background-color: tomato;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="root"></div>


来源:https://stackoverflow.com/questions/65691901/how-can-i-pass-state-from-page-to-component-and-back-to-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!