84669인 학습
152542인 학습
20005인 학습
5487인 학습
7821인 학습
359900인 학습
3350인 학습
180660인 학습
48569인 학습
18603인 학습
40936인 학습
1549인 학습
1183인 학습
32909인 학습
父组件我知道的有 props,但是只可以一级一级往下传,或者用context,或者用redux
那么子组件直接往上多级传递数据呢?一级一级用回调或者ref感觉太烦琐了,而redux用起来个人感觉也不是那么便捷,是否有类似context这样能直接传递多级数据的方法?
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...
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 只应该用在顶层组件,不是用来向上传值的。
redux我也觉得太冗余,所以知道了mobx,用起来真是酸爽
父组件通过props传函数给子,子调用函数传参回调
可以使用事件订阅这样的东西:
不过建议用 redux
redux的一个作用就是在于在多个不相邻组件之间传值,redux并非不便捷,只是使用redux需要思维方式有一点点转变。习惯后,你会觉得特别好(PS:通过ref往上传值,貌似并非好的React使用模式)。
就是一级级向上传,it's just how React works.Redux 只应该用在顶层组件,不是用来向上传值的。