在ReactJs中未定义引用

时间:2020-07-27 13:14:24

标签: reactjs ref

当我尝试在ref内使用滑块functionB时,出现ref undefined错误。我在这里做什么错了?

class somecomp extends Component {
  
 constructor(props){
   super(props);
   this.slider = React.createRef;   
 }

 componentDidMount(){        
   this.functionA();
 }

 functionA = () => {
   functionB();
 }

 functionB = () => {   
   // When i call slider ref here im getting ref undefined  
 }
   
 render() {     
   return (
     <div ref={slider => (this.slider = slider)}></div>                                                          
   );
 }
}

export default somecomp;

2 个答案:

答案 0 :(得分:0)

我在这里假设您问题的根源

this.slider = React.createRef

您不是通过传递引用来创建滑块的功能

尝试以这种方式使用它

this.slider = React.createRef();

也是这个

<div ref={slider => (this.slider = slider)}></div>

可能会简化为此

<div ref={this.slider}></div>

也不要忘记给用户ref的current属性 根据您的情况

const node = this.slider.current;

答案 1 :(得分:0)

您的代码中很少有应纠正的问题https://codesandbox.io/s/determined-lamport-gfv9j

class somecomp extends Component {
  
 constructor(props){
   super(props);
   this.slider = React.createRef; // use React.createRef() at here  
 }

 componentDidMount(){        
   this.functionA();
 }

 functionA = () => {
   functionB(); // use this.functionB() at here
 }

 functionB = () => {  
    console.log("this.slider", this.slider); 
   // When i call slider ref here im getting ref undefined  
 }
   
 render() {     
   return (
     <div ref={slider => (this.slider = slider)}></div>                                                          
   );
 }
}

export default somecomp;