【问题标题】:I dont know how to fix useSprint using class我不知道如何使用类修复 useSprint
【发布时间】:2021-12-26 01:30:05
【问题描述】:

我收到了这个错误:

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);

【问题讨论】:

  • 错误非常清楚,您还在寻找什么?您应该在功能组件中使用hooks
  • 你需要将类Component转换为功能组件,然后使用钩子。
  • 我不知道该怎么做,如果我知道我不会问。

标签: reactjs react-spring


【解决方案1】:

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

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

以下是代码框链接供您参考: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);

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 2017-01-11
    • 2014-04-15
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多