我不知道如何使用 class 修复 useSprint

I dont know how to fix useSprint using class

我收到这个错误:

Line 21:28:  React Hook "useSpring" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks.

我想使用不透明度进行过渡,当我单击按钮时图像出现或消失。

import React, { Component } from 'react';
import { withTranslation } from 'react-i18next';
import { useSpring, config, animated } from "react-spring";

import './Experience.css';



  class Experience extends Component {
      
    constructor(props) {
        super(props);
        this.state = {
            showA: false
        };
      }

    render() {

        // const [showA, setShowA] = useState(false);
        const fadeStyles = useSpring({
          config: { ...config.molasses },
          from: { opacity: 0 },
          to: {
            opacity: this.state.showA ? 1 : 0
          },
        });

        return (
          <div style={{ padding: "15px" }} className="App">
            <h2>Fade Demo</h2>
            <div>
              <animated.div style={fadeStyles}>
              <img  src={`https://a.wattpad.com/useravatar/valery2080.256.603024.jpg)`} alt="hola"/>
              </animated.div>
              <br />
              <button onClick={() => this.setState(val => !val)}>Toggle</button>
            </div>
      
          </div>
        );
    }
  }
  
export default withTranslation()(Experience);

您需要将 class 组件转换为功能组件。下面是体验组件到功能组件的实现。

注意:确保在您的实施中添加 CSS 文件。

以下是codesandboxlink供大家参考:https://codesandbox.io/s/jolly-wescoff-bnqm4

import React, { useState, Component } from "react";
import { withTranslation } from "react-i18next";
import { useSpring, config, animated } from "react-spring";

const Experience = () => {
  const [showA, setShowA] = useState(false);

  const fadeStyles = useSpring({
    config: { ...config.molasses },
    from: { opacity: 0 },
    to: {
      opacity: showA ? 1 : 0
    }
  });
  return (
    <div style={{ padding: "15px" }} className="App">
      <h2>Fade Demo</h2>
      <div>
        <animated.div style={fadeStyles}>
          <img
            src={`https://a.wattpad.com/useravatar/valery2080.256.603024.jpg)`}
            alt="hola"
          />
        </animated.div>
        <br />
        <button onClick={() => setShowA(!showA)}>Toggle</button>
      </div>
    </div>
  );
};
export default withTranslation()(Experience);