React项目指导

60次阅读

共计 2391 个字符,预计需要花费 6 分钟才能阅读完成。

原文链接:React 项目详解 GITHUB:react-webpack-config 持续更新 …
React 项目指导
使用 webpack 需要安装的依赖

webpack,webpack-cli,react,react-dom

babel-loader,@babel/core,@babel/preset-env,@babel/preset-react

设置.babelrc,{“presets”: [“@babel/preset-env”,”@babel/preset-react”]}

设置 scripts:
“dev”: “webpack –mode development”,
“build”: “webpack –mode production”

设置 webpack-dev-server:
devServer: {
compress: true,
port: 9000,
hot: true
},

“start”: “webpack-dev-server –config webpack.config.js”

设置 performance:
performance: {
hints: false
}

Component

基本组件
let title = <h1>Hello, world!</h1>

ReactDOM.render(title,document.getElementById(‘root’))

动态组件
import React from ‘react’;
import ReactDOM from ‘react-dom’;

let displayTime = () => {
let nowTime = (
<div>
<span> 现在时间:{new Date().toLocaleTimeString()}</span>
</div>
);
ReactDOM.render(t
nowTime,
document.getElementById(‘root’)
);
};

setInterval(displayTime, 1000);

class 组件构建器
import React, {Component} from ‘react’;
import ReactDOM from ‘react-dom’;

class HelloTitle extends Component {
render() {
return <h1>Hello,World!</h1>
}
}

ReactDOM.render(
<HelloTitle/>,
document.getElementById(‘root’)
);

props 属性
import React, {Component} from ‘react’;
import ReactDOM from ‘react-dom’;

class HelloTitle extends Component {
render() {
return <h1>Hello,{this.props.name}!</h1>
}
}

let titleDiv = (
<div>
<HelloTitle name=”React”/>
<HelloTitle name=”World”/>
</div>
);

ReactDOM.render(
titleDiv,
document.getElementById(‘root’)
);

props 多层使用
import React, {Component} from ‘react’;
import ReactDOM from ‘react-dom’;

class HelloTitle extends Component {
render() {
return <h1>Hello,{this.props.name}!</h1>
}
}

class HelloDiv extends Component {
render() {
return <div><HelloTitle name={this.props.name}/></div>
}
}

ReactDOM.render(
<HelloDiv name=”React”/>,
document.getElementById(‘root’)
);

组件复用
import React, {Component} from ‘react’;
import ReactDOM from ‘react-dom’;

class HelloTitle extends Component {
render() {
return <h1 style={this.props.style}>{this.props.content}</h1>
}
}

class HelloDiv extends Component {
render() {
return <div>
<HelloTitle content=” 比较大的字 ” style={{‘fontSize’: 18}}/>
<HelloTitle content=” 比较小的字 ” style={{‘fontSize’: 12}}/>
</div>
}
}

ReactDOM.render(
<HelloDiv/>,
document.getElementById(‘root’)
);

Component 的状态 state 和生命周期

state 属性
constructor(props) {
super(props);
this.state = {
time: new Date().toLocaleTimeString()
}
}

render() {
return <h1> 现在时间是 {this.state.time}</h1>
}
组件构建完成后先执行的动作,componentDidMount():
componentDidMount() {
let upTime = () => {
this.setState({time: new Date().toLocaleTimeString()})
};
setInterval(upTime, 1000)
}

setState() 修改状态值
this.setState({time: new Date().toLocaleTimeString()})

正文完
 0