使用环境:
- node -vv10.19.0
- npm -v6.13.4
- VSCode
创建一个全新的项目 https://blog.youkuaiyun.com/qq_39768189/article/details/105406702,这里就不多说了,
1、创建后:基本结构如下
我这里为了学习,删除src下所有的文件,创建一个空的index.js
使用该快捷键:Ctrl+·
输入命令:npm start
会发现能正常启动,出现一个空白的页面
2、类组件:有2中方式
这里直接在index.js 中写入
这里我们需要导入
import React, {Component} from 'react';
import ReactDOM from 'react-dom'
我这里学习,所有的文件都是放在src下面。同级
第一种:箭头函数
import React, {Component} from 'react';
import ReactDOM from 'react-dom'
//创建组件得第一种方式(箭头函数:名称要大写开始)
const App = (props) =>{
return (
<div>
{/* 只要在jsx插入js得代码,需要加花括号,注释也是js */}
<h1>welcome {props.title}!!!</h1>
<p>优秀的{props.title}</p>
</div>
)
}
//元素
// const app = createApp({title:"React 10"})
ReactDOM.render(
<App title = "2020年4月9日"/> ,
document.querySelector("#root")
)
第二种:类
为了方便,第一种方式index.js修改为index1.js
新创建index.js
import React,{Component} from 'react';
import {render} from 'react-dom'
import classNames from 'classnames'
import './index2.css'
//使用style样式
const style = {color: "#F00"};
const Header =() => <h1 style={style}>类组件!!!!</h1>
//定义组件得第二种方式,使用类
class App extends Component{
render(){
return (
<div>
<Header />
<p>{this.props.title}</p>
<h2 style={style}>使用style内联创建!!</h2>
<p className="has-test-red">使用class得方式,但是在react里class要写成className</p>
<li className={classNames('a',{"b":true})}>要动态添加不同得className就可以使用第三方得包叫classNames</li>
</div>
)
}
}
//类组件渲染得原理
// const app = new App({
// title:"类组件使用得是:React.Component!!!"
// }).render()
render(
// <h1>类组件</h1>,
<App title="类组件使用得事:React.Component"/>,
// app,
document.querySelector("#root")
)
我这里使用了样式:index2.css
.has-test-red{
color: rgb(182, 206, 50);
}