简体   繁体   English

如何从另一个组件触发 state 在 Reactjs

[英]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 APP的示例结构

  • Home.js主页.js
    • Component which has the progress bar (Component 1)具有进度条的组件(组件 1)
      • Component in Between (Component 2)介于两者之间的组件(组件 2)
        • Component where I want to trigger the progress bar from (Component 3)我想从中触发进度条的组件(组件 3)
  • ProgressBar component (ProgressBar)进度条组件(ProgressBar)

https://codesandbox.io/s/optimistic-stallman-rjxi9?file=/src/App.js 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.我想从组件 3执行onClick以更改位于组件 1中的进度条 state 但中间有一个组件以及它自己的组件上的进度条。

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.我尝试的是将 function 通常传递给我想从(组件 3 )触发该操作的组件中的新 function 并将该 ZC1C425268E68385D1AB5074C17A94F 传递给按钮。 but it gets an error "Type error this.props.* is not a function"但它收到错误“类型错误 this.props.* 不是函数”

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您需要使 Component2 (C2) 和 Component3 (C3) 成为 Component1 的子项,并将handleProgress作为道具传递给 Component2 和 Component3 就像这里https://codesandbox.io/s/blue-lake-6mx7o?fontsize=14&hidenavigation =1&主题=深色

For now, you created a function handleProgress in C1, but you never passed it to C2 and C3.现在,您在 C1 中创建了一个handleProgress ,但您从未将它传递给 C2 和 C3。

To pass it to C2 and C3, you need to remove them from App component, and move them to C1.要将其传递给 C2 和 C3,您需要将它们从App组件中移除,并将它们移动到 C1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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