$ npx create-react-app <project-name>
# 创建项目
三个包:
- React 核心包
- React-dom 在浏览器渲染 DOM
- React-scripts 封装的 webpack 配置
{
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
}
四个命令:
- start 开发环境下运行
- build 项目打包(生产环境)
- test 测试任务
- eject 弹出 webpack 配置
语法
JSX
JSX 是一种 JavaScript 的语法扩展,可以看做为一种模板语法,但也具有 JavaScript 的所有功能
注意:在 React 16 中必须引入 React 才能使 JSX 生效
组件
函数组件
const Element = function(props){
return <h1 title={ props.title } >hello { props.message }</h1>
}
ReactDOM.render({
<Element title="" message="" />,
document.querySelector('#root')
})
class组件
class Element extends React.Component {
/* constructor(option) {
this.option = option
}
*/
render() {
// return <h1>标题: hello {this.option.message}</h1>
return <h1>标题: hello {this.props.message}</h1>
}
}
ReactDOM.render({
<Header message="" />,
...
})
注意:
- 组件名称首字母大写,否则 React 会识别为 HTML 标签
- 函数组件本质上是一个函数,通过 props 接收
- 所有 HTML 标签必须要有一个根节点包裹(为了不产生额外的标签,可以使用
<React.Fragment></React.Fragment>
和<></>
) - class 组件必须实现一个 render() 方法
- class 组件必须继承 React.Component,使用 this.props 获取父传子的参数
组件通信
父子组件:
- 父传子: 通过在父组件上调用的子组件标签,绑定属性名和属性值,子组件使用 props 接收传参。
- 子传父:通过父组件上调用的子组件标签,绑定方法名和回调函数,子组件使用 props 接收并传参调用。
跨组件:
- 转化为父子通信模式
- 使用 React.createContext() 实例:
工具js
// 引入 react
import react from 'react'
// 创建相关实例
const xxContext = react.createContext()
// 从其中提取 provider 和 consumer
const { Provider, Consumer } = xxContext
// 导出
export {
xxContext,
Provider,
Consumer
}
需要传参的组件
// 使用 Provider 提供组件
<Provider value={{ // 使用对象传参更为方便
stateAttribute: stateAttributeValue // 属性名:属性值(或方法)
}}>
</Provider>
需要接收的组件
// 方法1 使用 Consumer 消费组件 在需要使用方法或参数的地方用 Consumer 包裹起来
<Consumer>
{
value => {
// 在所有参数和方法都在 value 里
return (
<div>
</div>
)
}
}
</Consumer>
// 方法2 使用 contextType 接收 react.createContext() 的实例,并以 this.context 调用其里面的属性方法
import { xxContext } from '路径'
class ...... extends Component {
static contextType = xxContext
return (
<div> { this.context.message } </div>
)
}
网友评论