受控組件
,由於其更符合react的思想,不須要進行DOM的操做,並且react也不推薦過多的使用refsclass Login extends React.Component { constructor(props){ super(props) this.state = { age:18 } this.handleSubmit = this.handleSubmit.bind(this) this.handleChange = this.handleChange.bind(this) } handleSubmit(event){ event.preventDefault(); // 經過舊的refs獲取username const username = this.refs.username.value // 經過新的refs獲取username const pwd = this.pwd.value // 經過狀態獲取age const {age} = this.state console.log(username,pwd,age); } handleChange(event){ // 因爲原生的onchange事件並非真的在change時觸發事件,而是在失去焦點的時候纔會觸發change事件 // react在onChange事件作了優化,會在change的時候就觸發事件 const age = event.target.value this.setState({ age }) } render(){ return ( <form action="" method="get" onSubmit={this.handleSubmit}> <p> username: <input type="text" ref="username" /> </p> <p> password: <input type="password" ref={input => this.pwd = input} /> </p> <p> age: <input type="number" value={this.state.age} onChange={this.handleChange} /> </p> <p> <input type="submit" value="login" /> </p> </form> ) } } ReactDOM.render(<Login/>,document.getElementById('app'))
// 定義組件 class Life extends React.Component{ constructor(props){ super(props) this.state = { opacity:1, color:`#f0f` } this.cancelTime = this.cancelTime.bind(this) } componentDidMount(){ // 定時器做用域問題 // 1. 經過bind解決 // 2. 箭頭函數 this.timer = setInterval( function() { let {opacity} = this.state opacity -= 0.1 //不能使用opacity === 0 // 由於js的計算存在偏差 if(opacity <= 0){ opacity = 1 } this.setState({ opacity }) }.bind(this),200) } cancelTime(){ // 移除組件 ReactDOM.unmountComponentAtNode(document.getElementById('app')) } componentWillUnmount(){ // 銷燬組件以前的勾子 // 定時器必須清除,否則會形成內存泄露的問題 clearInterval(this.timer) } render(){ const {msg} = this.props const {...style} = this.state return ( <div> <h1 style={style} >{msg}</h1> <button onClick={this.cancelTime}>取消定時器</button> </div> ) } } // 渲染組件 ReactDOM.render(<Life msg="生命週期演示"/>,document.getElementById('app'))
問題javascript
樣式綁定,首先將樣式存在state中,在render中將樣式幫上java
//方式2:綁定樣式 // 由於綁定樣式是在js中使用,因此樣式是使用對象的方式傳入 const {opacity,color} = this.state //這裏須要使用雙花括號,由於是在js中綁定樣式,樣式在一個對象中以鍵值對的形式存在 <h1 style={{opacity,color}} >{msg}</h1> //方式2:綁定樣式 // 使用...將樣式以對象的方式取出,能夠直接綁定至樣式上 const {...style} = this.state <h1 style={style} >{msg}</h1>
定時器必須清除,否則會形成內存泄露的問題react