【问题标题】:Ref undefined in ReactJs在 ReactJs 中引用未定义
【发布时间】:2020-11-16 19:56:50
【问题描述】:

当我尝试在 functionB 内使用滑块 ref 时,我收到了 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;

【问题讨论】:

  • 首先,createRef 是一个函数。您必须使用createRef() 调用它。从那里开始,否则您的问题似乎是一个错字。

标签: reactjs ref


【解决方案1】:

您在代码中遇到的一些问题应该被纠正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;

【讨论】:

    【解决方案2】:

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

    this.slider = React.createRef
    

    您不是创建 ref,而是将创建 ref 的函数传递给滑块

    尝试以这种方式使用它

    this.slider = React.createRef();
    

    还有这个

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

    可以简化成这样

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

    也不要忘记用户current ref 的属性 在你的情况下,它会是

    const node = this.slider.current;
    

    【讨论】:

    • 你有什么问题?
    • 我仍然得到 ref undefined
    • 我想你可能会忘记使用 current.常量节点 = this.slider.current;当您尝试访问参考时道具。请检查答案更新。
    • 我更新了原代码,这里请检查函数B是区间函数
    猜你喜欢
    • 2020-04-01
    • 2016-09-01
    • 2016-05-22
    • 2015-09-21
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2017-10-31
    • 2021-04-15
    相关资源
    最近更新 更多