/* * @Description: react基礎語法集錦,每天了解一點點 * @Version: 2.0 * @Autor: lhl * @Date: 2020-06-01 10:20:33 * @LastEditors: lhl * @LastEditTime: 2020-06-01 11:47:26 */
// props和state的不同?props 是傳遞給組件的(類似於函數的形參),而 state 是在組件內被組件自己管理的(類似於在一個函數內聲明的變量)
import React, { Component } from 'react' import _ from 'lodash'; export default class App extends Component { render() { return ( <div>
<p>hello react</p>
<Foo></Foo>
<Bar></Bar>
<LoadMore></LoadMore>
<Searchbox></Searchbox>
</div>
) } } class Foo extends Component { // 點擊事件
// 在 render 方法中使用 Function.prototype.bind 會在每次組件渲染時創建一個新的函數,可能會影響性能
// 在 render 方法中使用箭頭函數也會在每次組件渲染時創建一個新的函數,這會破壞基於恆等比較的性能優化。
// 函數傳遞參數的方式一
handleClick(id) { console.log('Click callback render箭頭函數',id,this); // 輸出 Click callback render箭頭函數 1 和 組件實例
} render() { return ( <div>
<button onClick={() => this.handleClick(1)}>Click Foo</button>
</div>
) } } class Bar extends Component { // 點擊事件
// 為什么我的函數每次組件渲染時都會被調用? 正確做法是,傳遞函數本身(不帶括號)
// 函數傳遞參數的方式二
handleClick(name){ console.log('Click callback',name,this); // 輸出 Click callback 'bob' 和 組件實例
} // react 通過 data-attributes 傳遞參數
handleClickGetAttributes = (e) =>{ console.log(e.target.dataset.id,e.target.dataset.url) // 1 https//www.baidu.com
} render() { return ( <div>
<p data-id="1" data-url="https//www.baidu.com" onClick={this.handleClickGetAttributes}>react獲取自定義屬性</p>
<button onClick={this.handleClick.bind(this,'bob')}>Click Bar</button>
</div>
) } } // 怎樣阻止函數被調用太快或者太多次? 節流 防抖 lodash庫提供了節流和防抖的函數 npm i lodash -S 安裝
class LoadMore extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleClickThrottled = _.throttle(this.handleClick, 1000); } // _.debounce、_.throttle 和 raf-schd 都提供了一個 cancel 方法來取消延遲回調。你需要在 componentWillUnmount 中調用該方法,或者對代碼進行檢查來保證在延遲函數有效期間內組件始終掛載
componentWillUnmount() { this.handleClickThrottled.cancel(); } render() { return <button onClick={this.handleClickThrottled}>Load More</button>;
} handleClick() { console.log(111) // 使其每秒鍾的只能調用一次
} } // 防抖確保函數不會在上一次被調用之后一定量的時間內被執行。當必須進行一些費時的計算來響應快速派發的事件時(比如鼠標滾動或鍵盤事件時),防抖是非常有用的
class Searchbox extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.emitDebounced = _.debounce(this.emitChange, 1000); } componentWillUnmount() { this.emitDebounced.cancel(); } render() { return ( <input type="text" onChange={this.handleChange} placeholder="Search..." defaultValue={this.props.value} />
); } handleChange(e) { this.emitDebounced(e.target.value); } emitChange(value) { console.log(value,'value') // 1s 的延遲來改變文本輸入
} }