简体   繁体   English

React.JS,在组件之间传递数据

[英]React.JS, pass data between components

very new to react. 非常新的反应。 you can say I have not yet started to think like React. 你可以说我还没有像React那样思考。 here is the problem: 这是问题所在:

    <div>
    <DropDown>    </DropDown>
    <Panel>    </Panel>
    </div>

In the dropdown, I select a value. 在下拉菜单中,选择一个值。 Store it in state, as something as , currentLocation. 将其存储为state,如currentLocation。 Then I go to Panel, hit a button, and I want to open a modal. 然后转到面板,单击一个按钮,然后打开一个模态。 When i open a modal, I need to pass the currentLocation to that model. 当我打开模态时,我需要将currentLocation传递给该模型。 I can pass in arbitrary value to modal, but I cannot figure out a way to get the currently selected item from DropDown. 我可以将任意值传递给模式,但无法找到从DropDown获取当前选定项的方法。

How do I get the value of the currently selected item to the Panel? 如何获得面板中当前选定项目的价值? Am I even making sense? 我有道理吗?

When you call the setState in the dropdown that will force an update of the page. 在下拉菜单中调用setState时,将强制更新页面。 Then if you call this.state in your component you should have the value you need there. 然后,如果您在组件中调用this.state ,那么您应该在那里拥有所需的值。

You should go over the basic tutorials to grasp the react basics. 您应该阅读基础教程以掌握React的基础知识。

But it goes like this: 但它是这样的:

     getInitialState: function() {
        return {
          myVar: ''
          //set your variables here
          //getInitialState will get called before the component gets mounted
        };
      },
     myCustomFunction: function(newVariable) {
        this.setState({
          myVar: newVariable
        });
      },
     render: function() {
        return (
          <div>
      <input
        onChange={this.myCustomFunction}
        />
      <MyCustomComponent myProp={this.state.myVar}/>
           //everytime the state changes MyCustomComponent will have that new value as a prop 
          </div>
        );
      }

There is a lot of ambiguity in your question but I'll try for the simplest case. 您的问题有很多歧义,但我会尝试最简单的情况。

You have a Panel component and a Dropdown component. 您有一个面板组件和一个下拉菜单组件。

You want to the Panel to have access to a value that was set when the Dropdown was used. 您希望面板可以访问使用下拉菜单时设置的值。

Solution: When the Dropdown is actuated, it creates an Action that Stores the selected value. 解决方案:激活下拉菜单后,它将创建一个存储所选值的操作。

When the modal button in the Panel is actuated, it creates an Action that requires the DropDownStore. 当面板中的模式按钮被激活时,它将创建一个需要DropDownStore的动作。 Then it decides what to do based on that value. 然后,它根据该值决定要做什么。

The pattern I am loosely describing is known Facebook's Flux architecture which is basically just a more specific application architecture for React applications similar to pub/sub or an event bus. 我大致描述的模式是众所周知的Facebook的Flux架构,该架构基本上只是针对React应用程序的更特定的应用程序架构,类似于pub / sub或事件总线。

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

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