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

Categories

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

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

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


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

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...