初学react(三):state状态使用
程序员文章站
2022-03-11 16:29:43
...
React-state状态使用,类似vue里的data
a. state来自于react的Component,所以只能在类里面使用,不能再函数里使用
b. 用来改变值的状态
import React from 'react';
import './App.css';
import Persion from './Persion/Persion';
class App extends React.Component {
/**
* state: 用于改变组件内状态的值(动态)
* props: 用于组件通信传值
*/
state = {
persions: [
{
name: '渣渣辉',
count: '30'
},
{
name: 'aaa',
count: '20'
},
{
name: 'bbb',
count: '10'
},
{
name: 'ccc',
count: '5'
}
],
otherState: 'anything'
}
// 函数直接定义在于render同级别,因为class类下,用this.函数名来访问
switchNameHandLer = () =>{
console.log("hello")
// es6中this执行为当前类
//this.state.persions[0].name = '渣渣渣渣辉' //不要直接去更改state Use setState()
this.setState({
persions: [
{
name: '渣渣辉111',
count: '3000'
},
{
name: 'aaa',
count: '20'
},
{
name: 'bbb',
count: '10'
},
{
name: 'ccc',
count: '5'
}
]
})
}
render () {
return (
<div className="App">
hello world
{/* 函数不能加括号,加括号就直接执行了 */}
<button onClick={this.switchNameHandLer}>更改状态值</button>
<Persion name={this.state.persions[0].name}
count={this.state.persions[0].count}/>
<Persion name={this.state.persions[1].name}
count={this.state.persions[1].count}/>
<Persion name={this.state.persions[2].name}
count={this.state.persions[2].count}/>
<Persion name={this.state.persions[3].name}
count={this.state.persions[3].count}>
<a href='http://www.baidu.com'>非常感谢大家的支持</a>
</Persion>
</div>
);
}
}
export default App;