react 02 组件state click
一,组件
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; // 函数式组件 return function Hello(props) { let titleName = <p> 这是 Hello副标题 </p> return ( <div> <h1>今天天气:{props.weather} </h1> {titleName} </div> ) //在组件中 必须返回一个合法的虚拟jsx dom 元素 } // 类组件 class Hi extends React.Component { render() { return ( <div><h1>今天天气:{this.props.weather} </h1></div> ) } } ReactDOM.render( <div> <Hello weather="出太阳" /> <Hi weather="出太阳"/> </div>, document.getElementById('root') );
二,组件状态state
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; //这种写法组件不能自动更新 class Hello extends React.Component { // 状态-私有 constructor(props) { super(props) this.state = { time:new Date().toLocaleTimeString() } } // 视图 render() { // 下面不加eslint 报错 // eslint-disable-next-line this.state.time = new Date().toLocaleTimeString() return ( <div><h1>当前时间:{this.state.time}</h1></div> ) } } ReactDOM.render( <div> <Hello /> </div>, document.getElementById('root') ); setInterval(()=>{ // 反复渲染同一组件,不会重复渲染,所以要在render 的时候重新赋值 ReactDOM.render( <div> <Hello /> </div>, document.getElementById('root') ); },1000)
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class Hello extends React.Component { // 状态-私有 constructor(props) { super(props) this.state = { time:new Date().toLocaleTimeString() } console.log(this.state.time) } // 视图 render() { return ( <div><h1>当前时间:{this.state.time}</h1></div> ) } // 生命周期 componentDidMount() { setInterval(()=>{ // setState() this.setState({time:new Date().toLocaleTimeString()}) },1000) } } ReactDOM.render( <div> <Hello /> </div>, document.getElementById('root') )
三,点击事件
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class Hello extends React.Component { constructor(props) { super(props) this.state = { c1:'active', c2:'content' } // 改变show1 的this 指向 this.show1 = this.show1.bind(this) } render() { return ( <div> <button onClick={this.show}>不传参写法</button> <button onClick={()=>this.show('1')}>一</button> <button onClick={()=>this.show('2')}>二</button> {/* 此时show1 的this 指向的是button 所以要改一下指向 */} <button data-index="1" onClick={this.show1}>一</button> <button data-index="2" onClick={this.show1}>二</button> <div className={this.state.c1}>内容一</div> <div className={this.state.c2}>内容二</div> </div> ) } show(arg) { console.log(arg) if(arg === '1') { this.setState({ c1:'active', c2:'content' }) }else { this.setState({ c2:'active', c1:'content' }) } } show1(e) { console.log(e.target.dataset.index) let arg = e.target.dataset.index if(arg === '1') { this.setState({ c1:'active', c2:'content' }) }else { this.setState({ c2:'active', c1:'content' }) } } } ReactDOM.render( <div> <Hello /> </div>, document.getElementById('root') )