react:子组件如何向上多级传递数据
高洛峰
高洛峰 2016-11-23 09:17:00
0
5
3173

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

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


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

répondre à tous(5)
三叔

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

三叔

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

三叔

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

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

三叔

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

三叔

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

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!