【问题标题】:ReactJS: How to pass information or communicate from one component to another or how to go on nextReactJS:如何将信息从一个组件传递到另一个组件或如何进行下一步
【发布时间】:2015-07-07 03:29:52
【问题描述】:

我仍然有点开始反应,我现在已经使用我的第二个解决方案 (here) 来显示/隐藏组件。

我现在的问题是,如果我有多个子元素并且我需要打开另一个组件(首选项)(我已经管理过,点击外部或其他地方会隐藏它)但同时我需要将信息传递给那个其他组件。我附上了我的小演示。我的问题再次是我如何从Child/Child2 组件传递说它是_preferences 或者它的坐标到Preferences 组件?

编辑:添加了 jsfiddle 链接。

整个代码sn-p:

<html>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.7.0/lodash.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react-with-addons.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <div id="render-here"></div>

    <script type="text/jsx">
      var Parent = React.createClass({
        getInitialState: function () {
          return { 
            showPreference: false,
            childComponents: 0
          };
        },
        shouldComponentUpdate: function() {
          console.log('parent should update');
          return true;
        },
        _click: function() {
          this.setState({childComponents: this.state.childComponents + 1});
        },
        _showPreference: function() {
          this.setState({showPreference: true})
        },
        _hidePreference: function() {
          this.setState({showPreference: false})
        },
        render: function() {
          var childComponents = [];

          _.times(this.state.childComponents, function(n) {
            if (n % 2)
              childComponents.push(<Child key={'foobar'+n} showPreference={this._showPreference} />)
            else
              childComponents.push(<Child2 key={'foobar'+n} showPreference={this._showPreference} />)
          }.bind(this));

          return(
            <div style={{height:'100%', width:'100%', border:'1px solid blue'}} onClick={this._hidePreference}>
              {this.state.showPreference ? <Preference /> : null}
              <div onClick={this._click}>Add components</div>
              {childComponents}
            </div>
          )
        }
      });

      var Preference = React.createClass({
        shouldComponentUpdate: function() {
          console.log('preference should update');
          return true;
        },
        _click: function(e) {
          e.stopPropagation();
        },
        render: function() {
          return(
            <div ref="pref" style={{position:'absolute', left: '250px'}} onClick={this._click}>
              <div>Some preferences here...</div>
            </div>
          )
        }
      });

      var Child = React.createClass({
        shouldComponentUpdate: function() {
          console.log('child should update');
          return true;
        },
        _preferences: ['child', 'preferences'],
        _click: function(e) {
          e.stopPropagation();
          this.props.showPreference();
        },
        render: function() {
          return(
            <div ref="me" onClick={this._click}>Child - click me for preference</div>
          )
        }
      });

      var Child2 = React.createClass({
        shouldComponentUpdate: function() {
          console.log('child should update');
          return true;
        },
        _preferences: ['child2', 'preferences'],
        _click: function(e) {
          e.stopPropagation();
          this.props.showPreference();
        },
        render: function() {
          return(
            <div ref="me" onClick={this._click}>Child 2 - click me for preference</div>
          )
        }
      });

      React.render(<Parent name="foobar" />, document.getElementById('render-here'));
    </script>
  </body>
</html>

jsfiddle link.

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    首先,永远不要在你的 React 组件中存储任意对象,就像你对 _preferences: ['child', 'preferences'] 所做的那样。组件中的任何数据都应该在该组件的state 内,或者作为props 传递给它。

    如果你在组件对象上放置一个这样的数组,它将在该组件的所有实例之间共享。如果您只有一个实例,您可能不会注意到它。但一旦你需要更多,它可能会咬你。通过使用 statesetState 对其进行变异,React 知道何时重新渲染您的组件。

    现在回答你的问题;您的 Parent 组件可能应该是在其状态下保存 preferences 对象的组件。然后Parent 组件将其作为道具传递给ChildChild2Preference 组件。如果ChildChild2Preference 想要修改该对象,Parent 会将回调作为道具传递给他们,他们可以调用它来告诉Parent 它应该被更改。比如:

    let React = require('react');
    
    let Parent = React.createClass({
      getInitialState() {
        return {
          preferences: {
            someKey: 'someValue'
          }
        };
      },
      changePreference(pref) {
        this.setState(state => {
          state.preferences[pref.name] = pref.value;
          return state;
        });
      },
      render() {
        return (
          <div>
            <Child 
              preferences={this.state.preferences} 
              onChangePreference={pref => this.changePreference(pref)} 
            />
            <Preference 
              preferences={this.state.preferences} 
              onChangePreference={pref => this.changePreference(pref)} 
            />
          </div>
        );
      }
    });
    

    【讨论】:

    • 嗨。仍在阅读您的答案,但 javascript 中的 =&gt; 是什么?你的语法和我的有点不同。
    • 我在代码中使用了一些即将推出的 Javascript 功能。 React 项目使用像 Babel 这样的编译器将 ES6 代码编译成 ES5 代码是很常见的,这让你可以使用今天的新特性,而不必等待浏览器实现它们。这:let func = pref =&gt; this.changePreference(pref) 就是所谓的箭头函数。它的 ES5 等效项是 var that = this; var func = function(pref) { return that.changePreference(pref); }
    猜你喜欢
    • 1970-01-01
    • 2019-12-02
    • 2022-06-10
    • 2022-11-01
    • 2020-12-30
    • 1970-01-01
    • 2023-01-30
    • 2020-12-14
    • 2018-03-07
    相关资源
    最近更新 更多