在反应中,如何在儿童改变时得到注意?

问题描述:

我正在创建这个类,名为Scrollable,如果子元素的宽度/高度超过某个值,它将启用滚动。这是代码。在反应中,如何在儿童改变时得到注意?

import React, { Component } from 'react'; 

const INITIAL = 'initial'; 

class Scrollable extends Component { 
    render() { 
    let outter_styles = { 
     overflowX: (this.props.x? 'auto': INITIAL), 
     overflowY: (this.props.y? 'auto': INITIAL), 
     maxWidth: this.props.width || INITIAL, 
     maxHeight: this.props.height || INITIAL, 
    }; 
    return (
     <div ref={el => this.outterEl = el} style={outter_styles}> 
     <div ref={el => this.innerEl = el}> 
      {this.props.children} 
     </div> 
     </div> 
    ); 
    } 
}; 

export default Scrollable; 

// To use: <Scrollable y><OtherComponent /></Scrollable> 

This works great。除了现在我想添加一个功能,使滚动总是滚动到底部。我对如何做一些想法:

this.outterEl.scrollTop = this.innerEl.offsetHeight; 

但这个只需要在this.props.children高度改变被调用。有没有关于如何实现这一目标的想法?

在此先感谢。

现在我有解决这个问题的想法。

因为我正在使用react-redux。问题在于我无法在此Scrollable组件上使用生命周期挂钩,因为this.props.children在更新内容时可能不一定会更改。

实现此目的的一种方法是使Scroll组件知道对数state中的对应值。所以当相关值更新时,我们可以向下滚动到底部。

滚动组件:

import React, { Component } from 'react'; 

const INITIAL = 'initial'; 

class Scrollable extends Component { 
    componentWillUpdate(){ 
    if(this.props.autoScroll){ 
     // only auto scroll when the scroll is already at bottom. 
     this.autoScroll = this.outterEl.scrollHeight - this.outterEl.scrollTop - Number.parseInt(this.props.height) < 1; 
    } 
    } 

    componentDidUpdate(){ 
    if(this.autoScroll) this.outterEl.scrollTop = this.outterEl.scrollHeight; 
    } 

    render() { 
    let styles = { 
     overflowX: (this.props.x? 'auto': INITIAL), 
     overflowY: (this.props.y? 'auto': INITIAL), 
     maxWidth: this.props.width || INITIAL, 
     maxHeight: this.props.height || INITIAL, 
    }; 
    return (
     <div ref={el => this.outterEl = el} style={styles}> 
     <div ref={el => this.innerEl = el}> 
      {this.props.children} 
     </div> 
     </div> 
    ); 
    } 
}; 

export default Scrollable; 

滚动容器:

import { connect } from 'react-redux'; 

import Scrollable from '../components/Scrollable'; 

const mapStateToProps = (state, ownProps) => Object.assign({ 
    state: state[ownProps.autoScroll] || false 
}, ownProps); 

export default connect(mapStateToProps)(Scrollable) 

由此,Scrollable的生命周期钩将被称为相应的状态改变时。

我会推荐一个包element-resize-detector。它不是特定于React的,但您可以轻松地在其周围构建高阶组件或将Scrollable组件与其集成。

+0

谢谢你的建议。我同意这是一个很好的包。不过,我正在寻找比这更简单的解决方案,而且我认为我提出的解决方案更清晰,更容易推理。你怎么看? –

+0

这真的取决于。如果你只是寻找一个简单的,它是绝对正确的,你有什么。 – Season