简体   繁体   中英

Invalid hook call due to useref

I want to implement a toggle on a view. It should toggle onPress. So to do that I want to set a constant to React.useRef(); but I get the following error:

在此处输入图片说明

This is the part of my code that causes the error:

import React, { useState, useRef } from "react";
...

const transition = (
  <Transition.Together>
    <Transition.In type="fade" durationMs={200} />
    <Transition.Change />
    <Transition.Out type="fade" durationMs={200} />
  </Transition.Together>
);

const ref = React.useRef();

class RestaurantDetailTemplate extends React.Component {
  orderToggle = () => {
    if (this.props.orderToggle === true) {
      return (
        <Transitioning.View
          style={styles.orderToggle}
          transition={transition}
          ref={ref}
        >
          <Text style={{ fontSize: 20 }}> Gesamtpreis</Text>
        </Transitioning.View>
      );
    }
  };

  render() {
    return;
    {
      this.orderToggle();
    }
  }
}

Thanks in advance!

You should use hook inside a functional component. But your component isn't a functional component. To use ref in class components (as your) you should use React.createRef() . In your case:

import React, { useState, useRef } from "react";
...

const transition = (
  <Transition.Together>
    <Transition.In type="fade" durationMs={200} />
    <Transition.Change />
    <Transition.Out type="fade" durationMs={200} />
  </Transition.Together>
);

class RestaurantDetailTemplate extends React.Component {
  ref = React.createRef();
  
  orderToggle = () => {
    if (this.props.orderToggle === true) {
      return (
        <Transitioning.View
          style={styles.orderToggle}
          transition={transition}
          ref={ref}
        >
          <Text style={{ fontSize: 20 }}> Gesamtpreis</Text>
        </Transitioning.View>
      );
    }
  };

  render() {
    return;
    {
      this.orderToggle();
    }
  }
}

You are using useRef in-class component. Convert your class component to a functional component like

const RestaurantDetailTemplate = (props) => {

const ref = useRef();


const orderToggle = () => {
        if(props.orderToggle === true){
            return (
                <Transitioning.View
                    style={styles.orderToggle}
                    transition={transition}
                    ref={ref}
                >
                    <Text style={{fontSize: 20}}> Gesamtpreis</Text>
                </Transitioning.View>
            )
        } else  {
        return null;
     }
    };

return(
  {orderToggle()}
)
}

export default RestaurantDetailTemplate;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM