组件
- 在前端,视图的片段
- 包含: 视图标记、事件、数据、其它的逻辑**、**外部的配置
组件一般是内部管理数据集合(state)
外部传入配置集合 (props)
//class版本
class Text extends React.Component{
constructor(props) {
super(props);
this.state = {
title: this.props.title
}
}
handleBtnClick() {
this.setState({
title: "This is Change"
})
}
render() {
return (
<div>
<h1>{ this.state.title }</h1>
<button onClick={ this.handleBtnClick.bind(this) }>changeTitle</button>
</div>
)
}
}
ReactDOM.render(
<Text title="This is a class Comp" />,
document.getElementById('app')
)
//=> hook版本 -> 简单的一批
function Text (props) {
const [title, setTitle] = React.useState(props.title);
return (
<div>
<h1>{ title }</h1>
<button onClick={ () => setTitle('This is Change')}>changeTitle</button>
</div>
)
}
ReactDOM.render(
<Text title="This is a class Comp" />,
document.getElementById('app')
)
- props: 多个属性传值时 可用 {...data}形式传值
组件渲染的过程
→ React 主动的执行组件
→ 将属性集合转为对象 props
→ 将对象作为 props 传入组件
→ 替换jsx中的props 或者 state中的变量
→ ReactDOM.render 将最终的React元素通过一系列操作转换成真实的dom尽心渲染
组件调用规范
→ 视图标记 为 HTML标签时
→ 大驼峰写法作为一个React 元素 如:
→ 组件转化React 元素 → 用 ReactDOM.createElement(Test, {title: 123})
组合组件
就是一个组件里面有多个其它的组件 → 可平级、可嵌套
属性props 和 状态state的区别在哪里
1 → state → 数据池,是组件内部管理数据的容器,组件内部可读写
2 → props → 属性池, 外部调用组件传来的属性集合
3 →** React的这里,数据属于谁,谁才有资格去操作数据**
注意:
React函数组件一定要是一个纯函数
- 纯函数能保证绝对的复用性
- 相同的入参保证返回相同的结果
- 纯函数不可以修改入参
//=> 纯函数
function add(a, b) {
return a + b;
}
//=> 非纯函数
function plus(a, b) {
a = a + 1;//改了入参了,配置的参数就是笑话了
return a + b;
}