React, ReactDOM, React.createElement, ReactDOM.render, JSX, props, state
构建用户界面
的javascript库
React.createElement(type, props, children)
ReactDOM.render(content, container, cb)
。content要渲染的内容,container要渲染的元素容器,cb,渲染完成后回调函数,不常用。<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
// 创建要渲染的元素
const el = React.createElement(
"h1",
null,
React.createElement("p", null, "this is p ele."),
React.createElement("p", null, "this is p ele.")
);
// 视图渲染
ReactDOM.render(el, document.querySelector("#app"), () => {
console.log("回调成功");
});
什么是jsx?
是基于javascript + xml 的一个语法扩展
为什么用jsx?
要创建元素,使用React.createElement可读性差,维护性也差。jsx语法增强要渲染元素的可读性可维护性
浏览器不识别jsx,怎么办?
引入babal.js将jsx转化为浏览器可以识别的js代码。
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="app"></div>
<script type="text/babel">
ReactDOM.render(
<div>
<header>这是头部内容</header>
<main>这是内容哦</main>
</div>,
document.getElementById('app')
)
</script>
const arr = [1,2,3,4,5];
<ul>
{
arr.map(item => {
return <li key={item}>{item}</li>
})
}
</ul>
className
React.Fragment
标签日常开发中,都会使用脚手架提高开发效率
npm i create-react-app -g
// 或者
yarn add create-react-app global
create-react-app <项目名称>
npm start
// or
yarn start
类组件:
- 必须继承自
React.Component
- 必须有
render
方法- render方法,必须
返回
要输出的节点
内容
// App.js
import React, {Component} from 'react';
class App extends Component {
render() {
return (
<div>
hello, react
</div>
)
}
}
export default App;
// index.js
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
// 父组件index.js
const arr = [1,4,5,7,0]
ReactDOM.render(
<App name="小美" arr={arr} />,
document.getElementById('root')
);
// 子组件 App.js
class App extends Component {
render() {
return (
// ⚠️此处可以取到父级传入的值
const {name, arr} = this.props;
<div>
hello, react
</div>
)
}
}
组件内部的状态值。可以用setState({key: value}) 来修改,修改后会自动同步视图。
定义state有2种方式
// 1. 直接在类里写state
class Xx extends Component {
state = {
active: true
};
}
// 2. 在类的constructor里定义this.state
class Xx extends Component {
constructor(props){
super(props);
this.state = {
active: true
}
}
}
// App.js
class App extends Component {
// 定义state的2种方式, 选择一种即可
// 1. 直接在类里写state
// state = {
// active: true
// };
// 2. 在类的constructor里定义state
constructor(props){
super(props);
this.state = {
active: true
}
}
render() {
return (
<div>
<button onClick={this.handleChange}>点我切换active</button>
<p>当前active状态是: {this.state.active ? 'true' : 'false'}</p>
</div>
)
}
// 事件定义
handleChange = () => {
this.setState({
active: !this.state.active
})
}
}
1-从零开始学react-认识react&jsx&props&state
2-从零开始学react-深入state,组件通讯,生命周期,受控组件
3-从零开始学react-其他api,初识hook
4-从零开始学react-hooks相关
5-从零开始学react - react-router-dom5
6-从零开始学react - redux相关
7-从零开始学react - 全家桶项目实战