reactjs - วัตถุ ref ที่จัดเก็บใน reducer ไม่มีคุณสมบัติ offsetTop
ฉันมีตัวสร้างแบบฟอร์มสอบถามที่ปรับเปลี่ยนได้แบบไดนามิก ฉันบันทึกวัตถุอ้างอิงของคำถามทั้งหมดลงในอาร์เรย์ในรีดิวเซอร์ ฉันต้องการเข้าถึงอ้างอิงจากทุกหน้าเพื่อเลื่อนผู้ใช้ไปที่คำถามเฉพาะ ปัญหาของฉันคือวัตถุที่เก็บไว้ไม่มี offsetTop ให้ใช้สำหรับเลื่อน
ไม่มีความแตกต่างระหว่างการใช้ callback ของ 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 เป็นวัตถุที่ถูกต้องที่เราสามารถเห็นในคอนโซล แต่ currentQuestionRef.current.offsetTop เป็นค่า undefined!!
คำตอบ #1
คุณควรใช้ ref กับคอมโพเนนต์ของ React เช่น <div>, <input/> และ ... ดังตัวอย่างดังต่อไปนี้:
render(){
return(
<div ref={this.myRef}>
//code comes here
<div/>
);
}
หรือคุณสามารถส่ง ref เป็น prop เข้าไปในคอมโพเนนต์อื่นได้
