经过上一篇的介绍之后对state有了一个基本的了解,那么这一篇就是对state的进一步了解。下面我们还是通过一个小案例来进一步了解。
需求:点击按钮,获取文本框里面的内容,然后添加到下面,点击刚才添加的数据进行删除。
我们直接对上一篇的代码进行修改
1.首先,给state一个变量用来存放获取文本框的数据。names就是要存放的变量,代码如下:
constructor(props){
super(props);
this.state = {
inputValue:'',
names:[]
}
}
2.修改btn的点击事件,把获取到的input数据放到names里面,目的是为了待会展示,代码如下:
handleBtnClick() {
const names = this.state.names;
names.push(this.state.inputValue);
this.setState({
names:names
});
}
这里面的代码还可以用ES6的语法来写,代码如下:
handleBtnClick() {
this.setState({
names:[...this.state.names,this.state.inputValue]
});
}
…arr这个展开式就是获取当前数组所有的数据,后面的一个变量就是新增的那个变量。
3.修改render()函数的返回内容,主要是添加了要显示的列表item,代码如下:
render(){
return (
<div>
<div>
<input onChange={this.handleInputChange.bind(this)} placeholder='input value and click btn' />
<button onClick={this.handleBtnClick.bind(this)}>click me</button>
</div>
<div>
<ul>
{
this.state.names.map((item,index)=>{
return <li key={index}>{item} <icon index={index} onClick={this.handleDelete.bind(this,index)}>×</icon></li>;
})
}
</ul>
</div>
</div>
);
}
上面代码中的this.state.names.map((item,index)=>{})是ES6对数组遍历的语法,index是下标,item是对应下标的值。另外这里需要注意的是,最外面的{}是JSX语法定义的,{}这个主要是获取变量的值。例如{index}显示的结果就是下标。这里给li了一个key,这个表示一个元素的索引,如果不给的话,控制台会报警告,所以还是给一个。这里还给icon标签了一个onClick事件,目的是点击的时候是否要删除,其代码如下:
handleDelete(index) {
if (window.confirm("delete?")) {
const names = this.state.names;
names.splice(index, 1);
this.setState({
names: names
});
}
}
需要强调的一点就是我们不要直接操作state本身的值,而是通过一个变量先接收到state的值,然后对其进行修改,改完之后再赋值给state对应的变量(据说直接修改会有性能影响)。
完整代码如下:
import React, {Component} from 'react';
class ParentComponent extends Component {
constructor(props){
super(props);
this.state = {
inputValue:'',
names:[]
}
}
handleInputChange(e){
this.setState({
inputValue:e.target.value
});
}
handleBtnClick() {
const names = this.state.names;
names.push(this.state.inputValue);
this.setState({
names:names
});
}
handleDelete(index) {
if (window.confirm("delete?")) {
const names = this.state.names;
names.splice(index, 1);
this.setState({
names: names
});
}
}
render(){
return (
<div>
<div>
<input onChange={this.handleInputChange.bind(this)} placeholder='input value and click btn' />
<button onClick={this.handleBtnClick.bind(this)}>click me</button>
</div>
<div>
<ul>
{
this.state.names.map((item,index)=>{
return <li key={index}>{item} <icon index={index} onClick={this.handleDelete.bind(this,index)}>×</icon></li>;
})
}
</ul>
</div>
</div>
);
}
}
export default ParentComponent;
其实state还有很多的操作,目前就介绍这么多。下面是几个参考的地址:
(1)https://www.jianshu.com/p/c6257cbef1b1
(2)http://www.runoob.com/react/react-state.html
(3)https://reactjs.org/docs/state-and-lifecycle.html
最后一个是官网的,看起来吃力,但是很有用。
注释:
对数组的操作如果不是很好的,参考:http://www.w3school.com.cn/jsref/jsref_obj_array.asp
这个里面列举了很多的方法,遗忘的及时去复习,当然最好是在用到的时候再去,记忆更加深刻。