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



我收到这个错误:

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

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

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

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

相关内容

  • 没有找到相关文章

最新更新