我正在使用 TypeScript 构建 React 应用程序。
我想创建按钮,滚动到主页上子组件的标题。
我在子组件中创建了一个引用,如下这个堆栈溢出 https://stackoverflow.com/questions/33796267/how-to-use-refs-in-react-with-typescript回答并(尝试)使用转发裁判 https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components在我的父组件上访问它。
export class Parent extends Component {
private testTitleRef!: RefObject<HTMLHeadingElement>;
scrollToTestTitleRef = () => {
if (this.testTitleRef.current !== null) {
window.scrollTo({
behavior: "smooth",
top: this.testTitleRef.current.offsetTop
});
}
};
render() {
return <Child ref={this.testTitleRef} />
}
}
interface Props {
ref: RefObject<HTMLHeadingElement>;
}
export class Child extends Component<Props> {
render() {
return <h1 ref={this.props.ref}>Header<h1 />
}
}
不幸的是当我触发时scrollToTestTitleRef
我收到错误:
Cannot read property 'current' of undefined
这意味着 ref 未定义。这是为什么?我究竟做错了什么?
EDIT:
Estus https://stackoverflow.com/users/3731501/estus帮助我创建了参考。但是当我触发scrollToTestTitleRef()
事件,它不滚动。
当我console.log
this.testTitleRef.current
我得到输出:
{"props":{},"context":{},"refs":{},"updater":{},"jss":{"id":1,"version":"9.8.7","plugins":{"hooks":{"onCreateRule":[null,null,null,null,null,null,null,null,null,null,null,null],"onProcessRule":[null,null,null],"onProcessStyle":[null,null,null,null,null,null],"onProcessSheet":[],"onChangeValue":[null,null,null],"onUpdate":[null]}},"options":{"plugins":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}},"sheetsManager":{},"unsubscribeId":null,"stylesCreatorSaved":{"options":{"index":-99999999945},"themingEnabled":false},"sheetOptions":{},"theme":{},"_reactInternalInstance":{},"__reactInternalMemoizedUnmaskedChildContext":{"store":{},"storeSubscription":null},"state":null}
Note:我删除了以下键cacheClasses
, _reactInternalFiber
and
__reactInternalMemoizedMaskedChildContext
,因为它们包含循环依赖性。
所以当前似乎没有关键offsetTop
。这是否可能与以下事实有关:在我的实际应用程序中,子组件被包装在material-ui的内部withStyle
和 React-Redux'connect
?