react的state和setState
react的状态组件
react的有state的为状态组件,创建形式为:
import React, { Component } from "react";
import './index.css'
//有状态的组件 即有state
//jsx语句
class Box extends Component {
state={
num:1,
open: false,
}
add=()=>{
console.log(this);
this.setState({
num:this.state.num+1
});
this.setState({
open: !this.state.open
})
}
reduce(){
this.setState({
num: this.state.num-1
})
}
render() {
let open=this.state.open,
className=open?'index':'unindex';
return (
<div className={className}>
<button onClick={this.add}>点击我</button>
<div>我在持续增加哦:{this.state.num}</div>
<hr/>
<div onClick={()=>{this.reduce()}}>点击我可以减少</div>
</div>
)
}
}
export default Box;
无状态组件创建形式为:
import './App.css'; import Box from './index/index'; function App() { return ( <div className="App" id="app"> <header className="App-header"> <p> Edit <code>src/App.js</code> and save to reload. </p> <Box/> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;
即函数和class、component的区别。
浙公网安备 33010602011771号