简体   繁体   中英

How to trigger a state from another component In Reactjs

Hello world I need help with this.

I have a progress bar component and a component where I use the progress bar in it. And another component which supposes to trigger the progress bar.

Examples structure of the APP

  • Home.js
    • Component which has the progress bar (Component 1)
      • Component in Between (Component 2)
        • Component where I want to trigger the progress bar from (Component 3)
  • ProgressBar component (ProgressBar)

https://codesandbox.io/s/optimistic-stallman-rjxi9?file=/src/App.js

This is an example of what exactly I want to achieve and how I imagine it. the code doesn`t work but you will get the idea from the structure of the code.

I want to perform onClick from Component 3 to change the progress Bar state which is located in Component 1 but there is a Component in between as well as the progress bar on its own Component.

Things I tried is passing the function normally to a new function in the component that I want to trigger that action from ( Component 3 ) and pass that function to the button. but it gets an error "Type error this.props.* is not a function"

Thank you in advance

You need to make Component2 (C2) and Component3 (C3) to be children of Component1, and pass handleProgress as a prop to Component2 and Component3 like here https://codesandbox.io/s/blue-lake-6mx7o?fontsize=14&hidenavigation=1&theme=dark

For now, you created a function handleProgress in C1, but you never passed it to C2 and C3.

To pass it to C2 and C3, you need to remove them from App component, and move them to C1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM