【发布时间】: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