这是我参与更文挑战的第4天,活动详情查看: 更文挑战
前言 组件化开发流程:
- 分析页面可以拆分成几个组件, 定义并实现静态组件(死数据, 无交互)
- 动态数据注入, 交互功能实现;
- 封装抽取, 形成完善的组件。
一、props和state混合使用
案例 1:定义一个组件描述一条狗,
需求: 1、分析props和state的使用场景? 2、props的使用细节 3、单组件中,两者的区别?
核心代码:
1、定义props和state
//1.创建组件类
class Dog extends React.Component{
constructor(props){
super(props);
//2.设置state
this.state =
{
age:1,
dogFriends:[]
}
}
// 3.设置props属性的默认值
static defaultProps = {};
//4.设置props属性的类型
static propsTypes = {
name:PropTypes.string.isReuired,
gender:PropTypes.string.isRequired,
};
}
2、渲染页面
render(){
const {name,gender} = this.props;
const {age, dogFriends} = this.state;
return {
<div>
<p>够狗名:{name},性别{gender}</p>
<p>我今年{age}岁了</p>
<p>我又很多狗友</p>
<ul>
{dogFriends.map((friend,index)=><li key={index}>{friend}</li>)}
</ul>
<button onClick={this.addYear.bind(this)}>增一岁</button>
</div>
}
}
3、业务处理
addYear(){
//增加狗友
let tempArr = this.state.dogFriends;
tempArr.push('狗友'+Math.floor(Math.random() * 100 ));
this.setState({
age:this.state.age += 1
dogFriends:tempArr
})
}
案例总结:
在单组件中, props一般用于接收外部传入的数据; 而state则用于记录组件内部数据, 而且是需要经常改变的数据。
state是组件内部的状态(数据),不能够直接修改,必须要通过setState来改变值的状态,从而达到更新组件内部数据的作用。
props更多是组件间传递数据的一种方式,props同样也可以传递state。由于React的数据流是自上而下的,所以是从父组件向子组件进行传递;另外组件内部的this.props属性是只读的不可修改。
二、ref的使用
1、定义
Refs 提供了一种方式,用于访问在render方法中创建的DOM节点或React元素。
使用场景:
处理焦点、文本选择或媒体控制 触发强制动画 集成第三方DOM库。
注意:官方提示,如果可以通过声明式实现,则尽量避免使用refs。 画外音:React无法控制局面的时候,就需要直接操作Reaf了
2、案例使用
让输入框获得焦点?
代码展示
class CustomTextInput extends React.Component{
constructor(props){
super(props);
//绑定ref
this.myInput = React.createRef();
this.myBtn = React.createRef()'
this.focusTextInput = this.foucusTextInput.bind(this);
}
render(){
return (
<div>
<input type="text" ref={this.myInput} />
<input type="button" ref={this.myBtn} value="获取焦点" onClick=this.foucusTextInput} />
</div>
)
}
focusTextInput(){
this.myInput.current.focus();
console.log(this.myBtn)
}
}