安装react
老方法:
npm install -g create-react-app
create-react-app my-app
npx方式:
npx create-react-app my-app
npm i react-router-dom
npm i axios
cd my-app
npm start
虚拟DOM(JavaScript对象)与diff
- 虚拟DOM(JavaScript对象)
html:
<div id="main">
<input type="text" class="in" value="哈哈哈">
<ul>
<li>df</li>
<li>qwer</li>
</ul>
</div>
js:
var element = {
tagName: 'div', // 节点标签名
props: { // DOM的属性,用一个对象存储键值对
id: 'main'
},
children: [ // 该节点的子节点
{
tagName: 'input',
props: {
class: 'in',
type: "text"
},
children: ["哈哈哈"]
},
{
tagName: 'ul',
props: {},
children: [{
tagName: 'li',
props: {},
children: ["df"]
},
{
tagName: 'li',
props: {},
children: ["qwer"]
}
]
},
]
}
- diff
递归逐层比较
递归demo
digui = (a) => {
if (a == 1) {
return 1;//出口
}else{
return digui(a-1) + a;//调用自己递归
}
}
console.log(digui(100));
注意
- 组件名首字母大写
- state的使用
this.state={}
this.setState({})
this.setState({},callback())
- 路由
import { Route,BrowserRouter,Switch } from 'react-router-dom'
<BrowserRouter>
<Switch>
<Route path="/" component={ Main }></Route>
<Route path="/Login" component={ Login }></Route>
<Route path="/Login" component={ Login }></Route>
</Switch>
</BrowserRouter>
<Link to="/">Login</Link> = <a href="/">Login</a>
<Link to= {{ pathname: '/Login' }}>Login</Link> = <a href="/Login">Login</a>
函数中跳转(该路由要在路由管理中注册)
this.props.history.push("/One");
window.location.href="/One"
window.location.reload()
#npm run eject出错的话
git add .
git commit -m "init"
设置代理跨域,可能在package设置proxy不起作用,
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/api", {
"target": "http://mobilecdn.kugou.com/api/v3",
"secure": false,//安全性ssl https
"changeOrigin": true,//跨域
"pathRewrite": {
"^/api": ""
}
}));
};
使用的时候
axios..get('/api/search/song?format=json&keyword=3&page=1&pagesize=30&showtype=1').then(res => {
console.log(res);
})
- css
- 写在css文件中 list-style:none = listStyle:“none”
命名加.module
className={[${styles.a}
,${styles.b}
].join(’ ')}
import styles from './temp.module.css';
<div className={ styles.app }>A0</div>
- 写在js文件中
import React,{ Component } from 'react';
import { Link } from 'react-router-dom'
export default class App extends Component {
render(){
const Sty = {
listyle:{
listStyle: 'none'
}
}
return (
<div>
<ul>
<li style={ Sty.listyle }><Link to="/">Login</Link></li>
<li style={ Sty.listyle }><Link to="/One">One</Link></li>
<li style={ Sty.listyle }><Link to="/Two">Two</Link></li>
</ul>
{ this.props.children }
</div>
);
}
}
- url记得可能要有
http://
才能识别是url
qrUrl:"http://www.baidu.com"