我正在尝试滚动到自定义组件的位置,但引用它并不返回有效的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>
);
}
}
答案 0 :(得分:1)
您想要将ToggleContainer
的{{1}}更改为ContactUs
的顶部。
由于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>);
}
}