Javascript React-将功能组件更改为类组件
我有一些使用函数组件的代码,包括useEffect等,我想将这些代码转换为类,请帮助Javascript React-将功能组件更改为类组件,javascript,reactjs,function,class,components,Javascript,Reactjs,Function,Class,Components,我有一些使用函数组件的代码,包括useEffect等,我想将这些代码转换为类,请帮助 import * as React from "react"; export default function App() { const [isGreaterThan900px, setIsGreaterThan900px] = React.useState(false); React.useEffect(() => { function handleResize
import * as React from "react";
export default function App() {
const [isGreaterThan900px, setIsGreaterThan900px] = React.useState(false);
React.useEffect(() => {
function handleResize() {
if (window.innerWidth > 900) {
setIsGreaterThan900px(true);
} else {
setIsGreaterThan900px(false);
}
}
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return (
<div className="App">
<h1>is greater than 900 px: {isGreaterThan900px ? "true" : "false"}</h1>
</div>
);
}
import*as React from“React”;
导出默认函数App(){
常数[Isgreetherthan900px,SetIsgreetherthan900px]=React.useState(false);
React.useffect(()=>{
函数handleResize(){
如果(window.innerWidth>900){
设置大于900px(真);
}否则{
设置大于900px(假);
}
}
handleResize();
addEventListener(“调整大小”,handleResize);
return()=>window.removeEventListener(“resize”,handleResize);
}, []);
返回(
大于900 px:{大于900 px?“真”:“假”}
);
}
这是对React类组件的原始转换
import * as React from "react";
import { setState } from "react";
export default class App extends React.Component {
constructor(props) {
super(props);
this.handleResize = this.handleResize.bind(this.handleResize);
this.state = {
isGreaterThan900px: false
};
}
handleResize() {
if (window.innerWidth > 900) {
this.setState({ isGreaterThan900px: true });
} else {
this.setState({ isGreaterThan900px: false });
}
}
componentDidMount() {
this.handleResize();
window.addEventListener("resize", this.handleResize);
}
componentDidUpdate() {
this.handleResize();
// window.addEventListener("resize", this.handleResize); <---- you should not create another listener on update because there is one already running since the component did mount
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
render() {
return (
<div className="App">
<h1>
is greater than 900 px: {this.state.isGreaterThan900px ? "true" : "false"}
</h1>
</div>
);
}
}
import*as React from“React”;
从“react”导入{setState};
导出默认类App扩展React.Component{
建造师(道具){
超级(道具);
this.handleResize=this.handleResize.bind(this.handleResize);
此.state={
大于900px:错误
};
}
handleResize(){
如果(window.innerWidth>900){
this.setState({isGreaterThan900px:true});
}否则{
this.setState({isGreaterThan900px:false});
}
}
componentDidMount(){
这个.handleResize();
window.addEventListener(“resize”,this.handleResize);
}
componentDidUpdate(){
这个.handleResize();
//window.addEventListener(“resize”,this.handleResize);您应该尝试演示您尝试的内容以及遇到的问题,以便有人能够帮助您。我已经演示了要转换为类组件的代码