ref返回null值reactjs。如何处理?

问题描述 投票:0回答:1

我通过在reactjs中使用ref从另一个组件打开模态。因为我在下面的代码。

otpModalRef = ({onOpenModal}) => {
       this.showModal = onOpenModal;
}

并在代码下面呈现

<div className="otp_modal">
    <Otp ref={this.otpModalRef} ></Otp>
</div>

然后通过this.showModal();调用注册函数它工作正常。但当我点击登录按钮时,它给了我TypeError: Cannot read property 'onOpenModal' of null。以下是登录和注册功能。

    login = (e) => {
    e.preventDefault();
     axios.post('/api/signin', { 
                    user:this.state.user,
                    password:this.state.login_pass,
                })
      .then(res => {
            console.log(res);
            this.context.router.history.push({
                    pathname:'/',
                });

      })
      .catch(function (error) {
        console.log(error.message);
      })
}

register = (e) => {
    e.preventDefault();     
    axios.post('/api/user/add', { 
                    firstname: this.state.fname,
                    lastname:this.state.lname,
                    email:this.state.emailaddress,
                    password:this.state.password,
                    mobile:this.state.mobile 
                },              
            )
      .then(res => {
            console.log(res);
            this.showModal();
      })
}

没有得到什么问题?如果我评论otpModalRef它重定向到主页,但如果我保持给出这个null错误。

javascript reactjs
1个回答
2
投票

您需要调用React.createRef()来创建句柄,而不是像在roure代码中那样。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.otpModalRef = React.createRef();
  }
  render() {
    ...
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.