我得到了一个应用程序,它正在使用类组件进行响应,我找到了一个特性代码,我想将它添加到代码中,但它是使用函数组件生成的。代码在这里,https://codesandbox.io/s/framer-motion-animate-in-view-gqcc8,但相关部分是这样。
import { useInView } from "react-intersection-observer";
import { motion, useAnimation } from "framer-motion";
import "./styles.css";
function Box() {
const controls = useAnimation();
const [ref, inView] = useInView();
useEffect(() => {
if (inView) {
controls.start("visible");
}
}, [controls, inView]);我不知道如何在类组件中添加该控件变量
class App extends Component {
constructor(props) {
super(props);
this.state = {
curtains: null,
loading: true,
renderNav: false
};
}我应该把它加在我的州里吗?我不知道如何使它在类组件中工作
发布于 2020-03-10 17:08:35
不能在类组件的内部使用钩子。您可以做的是编写一个小包装器,它在呈现道具中公开ref和controls:
const Controls = ({children}) => {
const controls = useAnimation();
const [ref, inView] = useInView();
useEffect(() => {
if (inView) {
controls.start("visible");
}
}, [controls, inView]);
return children(ref, controls);
};然后你可以像这样使用它:
class App extends Component {
// ...
render() {
return (
<Controls>
{(ref, controls) => (
<motion.div ref={ref} animate={controls}>
{/* content */}
</motion.div>
)}
</Controls>
);
}
}发布于 2020-03-10 17:04:32
让我们说你有
const functionalComponent=()=>{
return <h1>Functional componenet</h1>
}您希望将其更改为类组件。
在顶部使用此导入:
import React,{Component} from "react";并将代码更改为如下所示:
Class functionalComponent extends Component{
state={}
render(){
return <h1>functional component</h1>;
}
}您的功能组件现在更改为类组件。
要在现有的类组件中使用它,不需要将功能组件更改为类组件,除非需要本地状态。
随着react钩子的引入,这也发生了变化,也就是说,如果您计划使用钩子,您就不必将您的功能组件更改为类组件。
在您的代码中: useEffect是一个钩子,不能在类组件中使用它。
我建议简单地导入类组件中的functional,如果您必须传递一些值,您可以将它作为一个支柱传递。
就导入功能组件而言:
import React,{Component} from "react";
import Box from "./Box.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
curtains: null,
loading: true,
renderNav: false
};
render(){
return(<Box/>);
}
}发布于 2020-03-10 16:58:01
您也可以像类组件一样在任何地方使用函数组件。顺便说一下,它也在使用,所以不需要担心不能在其中使用状态的东西。
使用:
<Box props={props}/>https://stackoverflow.com/questions/60622304
复制相似问题