状态(State) 和 属性(Props)
props 是组件对外的接口,state 是组件对内的接口。
组件内可以引用其他组件,组件之间的引用形成了一个树状结构(组件树),如果下层组件需要使用上层组件的数据或方法,上层组件就可以通过下层组件的props属性进行传递,因此props是组件对外的接口。组件除了使用上层组件传递的数据外,自身也可能需要维护管理数据,这就是组件对内的接口state。根据对外接口props 和对内接口state,组件计算出对应界面的UI。
主要区别:
- State是可变的,是一组用于反映组件UI变化的状态集合;
- Props对于使用它的组件来说,是只读的,要想修改Props,只能通过该组件的父组件修改。 在组件状态上移的场景中,父组件正是通过子组件的Props, 传递给子组件其所需要的状态。
React 属性(Props)的使用
Props(属性)默认为 “true”,当一个组件被注入一些属性(Props )值时,属性值来源于它的父级元素,所以人们常说,属性在 React 中是单向流动的:从父级到子元素。
组件像一个函数一样,接受特定的输入(props),产出特定的输出(React elements)
实例:
import React from 'react';
class NameCard extends React.Component{
render(){
const{name, number, isHuman, tags} = this.props
return(
<div className="alert alert-success">
<h4>{name}</h4>
<ul>
<li>电话:{number}</li>
<li>{isHuman ? '人类' : '外星生物'}</li>
<p>
{ tags.map((tag, index) => (
<span className="badge badge-pill badge-primary" key={index}>{tag}</span>
))}
</p>
</ul>
</div>
)
}
}
// ES6函数写法 同上面展示效果一样
const NameCard = (props) => {
const { name, number, isHuman, tags } = props
return (
<div className="alert alert-success">
<h4>{name}</h4>
<ul>
<li>电话:{number}</li>
<li>{isHuman ? '人类' : '外星生物'}</li>
<p>
{tags.map((tag, index) => (
<span className="badge badge-pill badge-primary" key={index}>{tag}</span>
))}
</p>
</ul>
</div>
)
}
export default NameCard;
React 状态(State)
状态是私有的,完全受控于当前组件,属性是外部传人的,不可改变,状态是可以改变,但不能随意改变。
- 组件内部的数据 可以动态改变
this.setState()
是更新state
的唯一方法
React 生命周期
- 组件初始化
- 组件更新
- 组件卸载