在化简器中存储的引用对象没有 offsetTop 属性



我有一个动态调查表单生成器。我将所有问题的 ref 对象保存到化简器中的一个数组中。我想从所有其他页面访问参考文献以将用户滚动到特定问题。我的问题是存储的对象没有用于滚动的 offsetTop。

是否使用 ref 的回调没有区别。

class Question extends React.Component<QuestionProps,{}>{
    myRef:any;
    constructor(props:QuestionProps){
        super(props);
       ...
        this.myRef = React.createRef();   // Create a ref object 
    }
...
render(){
        const {question,activeQuestionId} = this.props;
        const active = activeQuestionId === question.id;
        return <Row ref={this.myRef} className="QuestionBox" style={{opacity:active?1:0.2}} onClick={this.handleQuestionClick}>

在减速器中,我有:

case SET_QUESTION_ACTIVE:
        console.log(state);
        const currentRef = state.refs.filter(c=> c.questionId === action.payload.questionId);
        if (currentRef.length > 0) {
          const currentQuestionRef = currentRef[0].ref;
          window.scrollTo(0, currentQuestionRef.current.offsetTop);
        }

currentQuestionRef.current是我们可以在控制台中看到的正确对象。但是当前问题参考.当前.偏移顶部是未定义的!!

你应该将 ref 与 react 组件一起使用,如 <div><input/> 和 ...如以下示例:

    render(){
     return(
    <div ref={this.myRef}>
     //code comes here
    <div/>
 );
}

或者,您可以将ref作为prop发送到另一个组件中。

最新更新