安装
npm install -g create-react-app
创建react项目
create-react-app hello-react
项目启动
切换到react项目目录
npm start
打包
npm run build
只有一个reactdom的导入不能加大括号
import ReactDOM from "react-dom";
jsx语法显示
import React from "react";
import ReactDOM from "react-dom";
const msg="hello react"
const flag = true;
const list = ['吃饭','睡觉','上钟']
function showFlag(){
if(flag){
return '显示'
}else{
return '隐藏'
}
}
const App = (
<div>
<h1>数据渲染</h1>
{msg}
<h1>属性绑定</h1>
<h1 title={msg}>属性绑定</h1>
<h1>三元运算符</h1>
{flag ? '显示' : '隐藏'}
<h1>函数判断</h1>
{showFlag()}
<h1>列表渲染</h1>
{
list.map(item=>{
return (<p key={item}>
{item}
</p>)
})
}
</div>
)
ReactDOM.render(App,document.getElementById("root"));
基本语法与样式绑定demo
import React, { Component } from 'react'
import rfc from './rfc'
import rcc from './rcc'
import classnames from 'classnames'
// import './App.css'
import app from './app.module.css'
export default class App extends Component {
state={
msg:'hello react',
isShow: true,
styleObj:{
color:red
}
}
constructor(){
super()
// 根据构造函数改变this的指向
this.handleClick = this.handleClick.bind(this)
}
render() {
const {isShow} = this.setState.isShow
return (
<div>
<div>
<h1 style={{color:red}}></h1>
{/* 或者 */}
<h1 style={{this.state.styleObj}}>style绑定样式</h1>
</div>
<h1 className='title'>文字颜色</h1>
<h1 className={classNames(['title','size'])}>App</h1>
{/* 可以放三目运算符 */}
<h1 className={classnames('title',size?this.state.isShow:'')}></h1>
{/* 可以放键值对 */}
<h1 className={classNames({title:true,size:true})}></h1>
{/* 可以放对象 */}
<h1 className={classNames(['title',{size:this.state.isShow}])}></h1>
<div>App</div>
<rfc></rfc>
<rcc></rcc>
<button onClick={this.handleClick}> 根据构造函数改变this的指向,点我</button>
<button onClick={this.handleClick.bind(this)}>使用bind改变this的指向</button>
<button onClick={(e)=>this.handleClick(e,1)}>使用箭头函数改变this的指向</button>
<button onClick={()=>this.toggle()}>toggle</button>
</div>
)
}
toggle(){
this.setState({
isShow: !this.state.isShow
})
}
handleClick(e,number){
console.log(this.state.msg)
}
// 或者直接定义箭头函数
// handleClick = ()=>{
// console.log(this.state.msg)
// }
}
styled-component样式依赖安装
npm i styled-component -save
state私有变量的用法
import React, { Component } from 'react'
export default class App extends Component {
constructor(){
super()
// 私有变量
this.state = {
count: 0
}
}
render() {
return (
<div>
<h1>当前计数值为:{this.state.count}</h1>
{/* 双向绑定 */}
<button onClick={()=>this.handleChangeOut()}>+</button>
</div>
)
}
//私有变量设置
handleChangeOut(){
// this.setState({
// count: this.state.count += 1
// })
this.setState({
count: '你好'
})
this.setState((nextState)=>{
return{
count: nextState.count+=1
}
})
}
}