How can I scroll a div to be visible in ReactJS?

前端 未结 9 1528
梦如初夏
梦如初夏 2020-12-04 15:25

I have a popup list which is a div that contains a vertical list of child divs. I have added up/down keyboard navigation to change which child is

9条回答
  •  独厮守ぢ
    2020-12-04 16:08

    Another example which uses function in ref rather than string

    class List extends React.Component {
      constructor(props) {
        super(props);
        this.state = { items:[], index: 0 };
        this._nodes = new Map();
    
        this.handleAdd = this.handleAdd.bind(this);
        this.handleRemove = this.handleRemove.bind(this);
       }
    
      handleAdd() {
        let startNumber = 0;
        if (this.state.items.length) {
          startNumber = this.state.items[this.state.items.length - 1];
        }
    
        let newItems = this.state.items.splice(0);
        for (let i = startNumber; i < startNumber + 100; i++) {
          newItems.push(i);
        }
    
        this.setState({ items: newItems });
      }
    
      handleRemove() {
        this.setState({ items: this.state.items.slice(1) });
      }
    
      handleShow(i) {
        this.setState({index: i});
        const node = this._nodes.get(i);
        console.log(this._nodes);
        if (node) {
          ReactDOM.findDOMNode(node).scrollIntoView({block: 'end', behavior: 'smooth'});
        }
      }
    
      render() {
        return(
          
      {this.state.items.map((item, i) => ( this._nodes.set(i, element)}>{item}))}
    {this.state.index}
    ); } } class Item extends React.Component { render() { return (
  • this.listItem = element }> {this.props.children}
  • ); } }

    Demo: https://codepen.io/anon/pen/XpqJVe

提交回复
热议问题