import React, { Fragment } from "react";
/*
Fragment相当于block标签,无实际意义在react解释后会被丢掉,也可以写 <></>,但空标签不能加任何属性,比如key;
这样既保证了无多层div嵌套,有保证了jsx的只有一个根标签
*/
import root from "../../index";
/*----------------------------------------------------类组件-----------------------------------------------------
1. state={count:1}-----this.setState({count:this.state.count+1})
2. 生命周期:componentDidMount/componentDidUpdate/componentwillUnmount
3. myRef=React.createRef()---<input ref={this.myRef}>----使用时:alert(this.myRef.current.value)
*/
export default class Count extends React.Component {
state = {
count: 1,
};
myRef = React.createRef();
componentDidMount() {
this.timer = setInterval(() => {
this.setState((state, props) => ({ count: state.count + 2 }));
}, 1000);
}
componentWillUnmount() {
//组件卸载之前,先清除定时器
clearInterval(this.timer);
}
add = () => {
// this.setState({count:this.state.count+1});//对象写法(语法糖)
this.setState((state, props) => ({ count: state.count + 1 })); //函数写法
};
unmount = () => {
root.unmount(document.getElementById("root")); //由于版本太高,迪欧版本写法:ReactDom.unmountComponentAtNode()
};
alertInfo = () => {
alert(this.myRef.current.value);
};
render() {
return (
<Fragment>
<input ref={this.myRef} />
<div>count是{this.state.count}</div>
<button onClick={this.add}>点我+1</button>
<button onClick={this.unmount}>卸载App</button>
<button onClick={this.alertInfo}>展示信息</button>
</Fragment>
);
}
}
/*--------------------------------------------------函数式组件(无状态,无this)-------------------------------------
1. useState: const [count,setCount]=useState()
2. useEffect模拟生命周期:
useEffect(()=>{
//执行副作用操作:ajax请求、定时器、订阅、手动更改真实dom。
return()=>{ //模拟componentwillUnmount
//做收尾工作:取消定时器、取消订阅
}
},[]);//(1). []不监听任何状态:componentDidMount;(2).若第二个参数不传,在每次render都会走;(3).[count]当状态改变时会走
3. useRef:
const myCount = React.createRef();---<input ref={myCount} />---使用时:alert(myCount.current.value);
*/
export default function Count() {
const [count, setCount] = React.useState(0);
const myCount = React.createRef();
React.useEffect(() => {
let timer = setInterval(() => {
setCount((count) => count + 2);
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
function add() {
setCount(count + 1); //新值覆盖旧值
// setCount((count) => count + 1); //函数写法
}
function unmount() {
root.unmount(document.getElementById("root")); //由于版本太高,迪欧版本写法:ReactDom.unmountComponentAtNode()
}
function alertInfo() {
alert(myCount.current.value);
}
return (
<Fragment>
<input ref={myCount} />
<div>count是{count}</div>
<button onClick={add}>点我+1</button>
<button onClick={unmount}>卸载App</button>
<button onClick={alertInfo}>展示信息</button>
</Fragment>
);
}
面试 - react - Hooks
最新推荐文章于 2023-05-27 21:00:33 发布