React项目详解-寒青-SegmentFault思否
程序员文章站
2022-09-19 22:38:19
原文链接:react项目详解github:react-webpack-config持续更新...
react项目指导
使用webpack需要安装的依赖
webpack,webp...
原文链接: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 = ( <p> <span>现在时间:{new date().tolocaletimestring()}</span> </p> ); 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 = ( <p> <hellotitle name="react"/> <hellotitle name="world"/> </p> ); 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 <p><hellotitle name={this.props.name}/></p> } } 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 <p> <hellotitle content="比较大的字" style={{'fontsize': 18}}/> <hellotitle content="比较小的字" style={{'fontsize': 12}}/> </p> } } 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()})