React基础-2: 组件
组件
⛵ 3.1 什么是组件
- 某个业务或者界面的抽象和封装
⛵ 3.2 创建组件
- 🎃
3.2.1 创建类组件 - 类组件中一定有一个
render方法,返回当前组件的内容 - 为什么没有使用
React还要引入呢? 因为jsx代码在执行前会去找React.createElement()
import React,{Component} from 'react'
class App extends Component {
render(){
return <div>Hello I am a component</div>
}
}
- 🎃
3.2.2 函数组件
// 首字母大写
const Person = () => {
return <div>Hello I am 函数型组件</div>
}
⛵ 3.3 组件属性
- 🎃
3.3.1 props 传递数据 - 组件中可以通过
props对象获取外部传递进来的数据
<Person name="leslie" age="20" />
<Person name="mary" age="22" />
// 类组件
class Person extends Component{
render(){
return (
<div>
<h3>Name: {this.props.name} </h3>
<h3>Age: {this.props.age} </h3>
</div>
)
}
}
// 函数组件
const Person = props => {
return (
<div>
<h3>Name: {props.name} </h3>
<h3>Age: {props.age} </h3>
</div>
)
}
-
props对象中存储的数据是只读的,不能在组件内部修改
-
当props数据源中的数据被修改后,组件中的接收到props数据会被同步更新(
数据驱动DOM) -
🎃
3.3.2 props 默认值
class App extends Component{
static defaultProps = {}
}
// 函数组件默认值的设置
function ThemeButton(props){
}
ThemeButton.defaultProps = {
theme: 'secondary',
label: 'Button text'
}
- 🎃
3.3.3 props children - 通过
props.children属性可以获取到调用组件时填充到组件标签内的内容
<Person>组件内部的内容</Person>
const Person = (props) => {
return (
<div>{props.children}</div>
)
}
- 🎃
3.3.4 单向数据流 -
- 在React中, 关于数据流动有一条原则: 单向数据流动, 从父组件到子组件
-
- 单向数据流特征要求我们共享数据要放置在上层组件中
-
- 子组件通过调用父组件传递过来的方法更改数据
-
- 当数据发生更改时, React会重新渲染组件树
-
- 单向数据流使组件之间的数据流动变得可预测,使得定位程序变得简单
⛵ 3.4 类组件状态 state
- 🎃
3.4.1 定义组件状态 类组件除了能够从外部(props)接收状态数据还可以拥有自己的状态(state),此状态在组件内可以被更新,状态更新DOM更新.- 组件内部的状态数据存储在组件类中的
state属性中,state属性值为对象类型, 属性名称固定不可修改
class App extends Component{
constructor(){
super()
this.state = {
person: {name: 'leslie',age: 20 }
}
}
render(){
return (
<div>
{/* 使用state */}
<p>Name: {this.state.person.name}</p>
<p>Age: {this.state.person.age}</p>
</div>
)
}
}
- 🎃
3.4.2 更改组件状态 state状态对象中的数据不可直接更改, 如果直接更改DOM不会被更新- 更改
state需要使用setState方法
class App extends Component{
constructor(){
super()
this.state = {
person: {name: 'leslie', age: 20 }
}
this.changePerson = this.changePerson.bind(this)
}
// 修改 state 状态
changePerson(){
this.setState({
person: {name: 'dora',age: 18}
})
}
render(){
return (
<div>
{/* 使用state */}
<p>Name: {this.state.person.name}</p>
<p>Age: {this.state.person.age}</p>
<button onClick={this.changePerson}>Button</button>
</div>
)
}
}
- 🎃
3.4.3 双向数据绑定 - 双向数据绑定是指: 组件类中更新了状态,DOM状态同步更新;
DOM更改了状态,组件类中同步更新,组件<=>视图 - 要实现双向数据绑定需要用到表单元素和
state状态对象 (只有表单元素才可以更改数据)
class App extends Component{
constructor(){
super()
this.state = {
name: 'leslie'
}
this.nameChanged = this.nameChanged.bind(this)
}
// 修改 state 状态
nameChanged(event){
this.setState({
name: event.target.value
})
}
render(){
return (
<div>
{/* 使用state */}
<p>Name: {this.state.person.name}</p>
<p>Age: {this.state.person.age}</p>
<Person name={this.state.name} changed={this.nameChanged}>Button</Person>
</div>
)
}
}
const Person = (props) => {
// onChange 绑定的就是 nameChange 方法
return <input type="text" value={props.name} onChange={props.changed} />
}
Keep learning

浙公网安备 33010602011771号