直接看官方文档的时候,发现里面有很多react语句,但我忘得差不多了,所以回过头看react
一、本地搭建开发环境
步骤:
- 确保你安装了较新版本的 node.js。
- 创建一个新的项目
npx create-react-app my-app
cd my-app
npm start
3.删除掉新项目中 src/
文件夹下的所有文件。
cd my-app
cd src
# 如果你使用 Mac 或 Linux:
rm -f *
# 如果你使用 Windows:
del *
# 然后回到项目文件夹
cd ..
4.在src下新建index.js,在文件顶部引入react和reactdom
import React from 'react';
import ReactDOM from 'react-dom';
5.小demo-实时输出时间
// 本地时间demo--输出每秒
class Clocks extends React.Component {
constructor(props){
super(props);
this.state = {
date: new Date()
};
// 如果不加这句,会有报错
this.tick = this.tick.bind(this)
}
componentDidMount(){
this.timeID = setInterval(this.tick,1000)
}
componentWillUnmount(){
clearInterval(this.timeID)
}
tick() {
this.setState({
date: new Date()
});
}
render(){
// eslint-disable-next-line no-unused-expressions
return(
<div>
<h1>localtime is {this.state.date.toLocaleTimeString()}.</h1>
</div>
)
}
}
class Apps extends React.Component {
render(){
return(
<div>
<Clocks />
<Clocks />
<Clocks />
</div>
)
}
}
ReactDOM.render(<Apps />,document.getElementById('root'))
demo2按钮切换
// 按钮切换
class Peosonal extends React.Component{
constructor(props){
super(props);
this.state = {
isLogin:true
}
}
handleBtn(){
console.log(1)
this.setState({
isLogin:!this.state.isLogin
})
}
render(){
return(
<div onClick={()=>this.handleBtn()}>
<button>{this.state.isLogin ? 'ON' : 'off'}</button>
</div>
)
}
}
ReactDOM.render(<Peosonal />,document.getElementById('root'))
// 事件---
function LoginIn(props){
return <h1>welcome!</h1>
}
function LoginUp(props){
return <h1>goodBy!</h1>
}
// 阻止组件渲染
function Warning(props) {
if (!props.isShow) {
return null
}
return <div>Warning!!!</div>
}
// 按钮切换--条件渲染
class Peosonal extends React.Component{
constructor(props){
super(props);
this.state = {
isLogin:true
}
}
handleBtn=()=>{
this.setState({
isLogin:!this.state.isLogin
})
}
render(){
return(
<div onClick={this.handleBtn}>
<button>{this.state.isLogin ? 'ON' : 'off'}</button>
{
this.state.isLogin ?<LoginIn />:<LoginUp />
}
<Warning isShow = {this.state.isLogin} />
</div>
)
}
}
ReactDOM.render(<Peosonal />,document.getElementById('root'))