2016-12-16 24 views
0

我想滾動到自定義組件的位置,但引用它沒有返回一個有效的html節點。方法「goToContactUs」應該執行該操作。這將是最好的方式來做到這一點?滾動到自定義組件

class Help extends Component { 
    constructor() { 
     super(); 

     this.goToContactUs = this.goToContactUs.bind(this); 
    } 

    goToContactUs() { 
     this.contactUs.scrollIntoView(); 
    } 

    render() { 
     return (
      <div> 
       <ToggleContainer 
        title={this.props.strings['Contact Us']} 
        show={this.props.help.showContactUs} 
        toggle={this.contactUsHandler} 
        ref={(div) => { this.contactUs = div }} 
       > 
        <ContactUs sendEmail={this.props.sendEmail} emailSuccess={this.props.help.emailSuccess} /> 
       </ToggleContainer>     
      </div> 
     ); 
    } 
} 

回答

1

你想改變ToggleContainerscrollTopContactUs的頂部。

由於ContactUs將是該元素的一個實例,因此您可以使用findDOMNode來獲取其節點表示形式。

import { findDOMNode } from 'react-dom'; 

class Help extends Component { 
    // ... omitted 
    scrollToContact() { 
    const yPos = findDOMNode(this.contact).offsetTop; 
    this.container.scrollTop = yPos; 
    } 

    contact = null; 
    container = null; 

    render() { 
    return (<div> 
     <ToggleContainer 
     title={this.props.strings['Contact Us']} 
     show={this.props.help.showContactUs} 
     toggle={this.contactUsHandler} 
     ref={container => this.container = container} 
     > 
     <ContactUs 
      ref={contact => this.contact = contact} 
      sendEmail={this.props.sendEmail} 
      emailSuccess={this.props.help.emailSuccess} 
     /> 
    </ToggleContainer>     
    </div>); 
    } 
}