登录

react:子组件如何向上多级传递数据

父组件我知道的有 props,但是只可以一级一级往下传,
或者用context,
或者用redux

那么子组件直接往上多级传递数据呢?一级一级用回调或者ref感觉太烦琐了,而redux用起来个人感觉也不是那么便捷,是否有类似context这样能直接传递多级数据的方法?


# React
高洛峰 高洛峰 2704 天前 3035 次浏览

全部回复(5) 我要回复

  • 三叔

    三叔2016-11-23 09:18:49

    redux我也觉得太冗余,所以知道了mobx,用起来真是酸爽

    回复
    0
  • 三叔

    三叔2016-11-23 09:18:37

    父组件通过props传函数给子,子调用函数传参回调

    回复
    0
  • 三叔

    三叔2016-11-23 09:18:13

    可以使用事件订阅这样的东西:

    var events = (function(){
      var topics = {};
      var hOP = topics.hasOwnProperty;
    
      return {
        subscribe: function(topic, listener) {
          // Create the topic's object if not yet created
          if(!hOP.call(topics, topic)) topics[topic] = [];
    
          // Add the listener to queue
          var index = topics[topic].push(listener) - 1;
          
          // Provide handle back for removal of topic
          return {
            remove: function() {
              delete topics[topic][index];
            }
          };
        },
        publish: function(topic, info) {
          // If the topic doesn't exist, or there's no listeners in queue, just leave
          if(!hOP.call(topics, topic)) return;
    
          // Cycle through topics queue, fire!
          topics[topic].forEach(function(item) {
              item(info != undefined ? info : {});
          });
        }
      };
    })();
    
    // 父组件
    class F extends React.Component {
      constructor(props) {
        super(props);
        
        events.subscribe('my', obj => {
          console.log('sub', obj);
        });
      }
      render() {
        return (
          <div>
            <C />
          </div>
         );
      }
    }
    
    // 子组件
    class C extends React.Component {
      constructor(props) {
        super(props);
      }
      componentDidMount() {
        events.publish('my', {
          url: 'msg'
        });
        
        setTimeout(() => {
          events.publish('my', {
            url: 'new msg'
          });
        }, 1000);
      }
      
      render() {
        
        return (
          <div>ccc</div>
         );
      }
    }
    
    ReactDOM.render(
      <F />,
      document.getElementById('app')
    );

    不过建议用 redux

    回复
    0
  • 三叔

    三叔2016-11-23 09:17:49

    redux的一个作用就是在于在多个不相邻组件之间传值,redux并非不便捷,只是使用redux需要思维方式有一点点转变。习惯后,你会觉得特别好(PS:通过ref往上传值,貌似并非好的React使用模式)。

    回复
    0
  • 三叔

    三叔2016-11-23 09:17:39

    就是一级级向上传,it's just how React works.Redux 只应该用在顶层组件,不是用来向上传值的。

    回复
    0
  • 取消 回复 发送