Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

javascript - React TS using ref to scroll UL element

I have a dynamically generated UL which is populated from a passed in array of strings, representing a log file contents.

I want to be able to do two things - scroll to the bottom on load, and also scroll to a particular line on load.

I used to have this working in JSX but since moving to TS I can't figure out how to use refs and the DOM. When it gets into scrollToBottom(), the messageList variable is null.

What have I missed?

class LogTailModalComponent extends React.Component<ILogtailModalProps>{
    private messageList: any = null;

    componentDidUpdate(prevProps: ILogtailModalProps) {
        if (!prevProps.logtailActive && this.props.logtailActive)
        {
            this.scrollToBottom();
        }
    }

    scrollToBottom() {
        if (this.props && this.props.logtailActive && !this.props.logScrollingPaused) {
            if (!this.messageList) return;
            const scrollHeight = this.messageList.scrollHeight;
            const height = this.messageList.clientHeight;
            const maxScrollTop = scrollHeight - height;
            var node = ReactDOM.findDOMNode(this.messageList) as HTMLUListElement;
            if (node != null) {
                node.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
            }            
        }
    }

public render() {
        return (
            <div>
                <ul className="collection" ref={ (ref) => this.messageList = (ref)}>
                {                                                  
                    this.props.logtailData.map((d:any) => {
                        return (
                            <li className="collection-item" key={d.LineNumber}>
                                {d.Text}
                            </li>
                        );
                    })
                 }
             </ul>
         </div>
    
question from:https://stackoverflow.com/questions/65843714/react-ts-using-ref-to-scroll-ul-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...