父組件經過props向子組件傳遞參數javascript
父組件將一個函數做爲props傳遞給子組件,子組件調用該回調函數,向父組件通訊。css
context是全局容器,靜態屬性,使用條件:html
若組件中使用constructor函數,務必在構造函數中傳入第二個參數context,並在super調用父類構造函數時也傳入context,不然會形成組件中沒法使用contextjava
constructor(props,context){ super(props,context); }
Throttle,阻止函數在給定時間內被屢次調用。react
import throttle from 'lodash.throttle'; class LoadMoreButton extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.handleClickThrottled = throttle(this.handleClick, 1000); } componentWillUnmount() { this.handleClickThrottled.cancel(); } render() { return <button onClick={this.handleClickThrottled}>Load More</button>; } handleClick() { this.props.loadMore(); } }
Debounce,確保函數上次執行後的一段時間內,不會再次執行。函數
import debounce from 'lodash.debounce'; class Searchbox extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.emitChangeDebounced = debounce(this.emitChange, 250); } componentWillUnmount() { this.emitChangeDebounced.cancel(); } render() { return ( <input type="text" onChange={this.handleChange} placeholder="Search..." defaultValue={this.props.value} /> ); } handleChange(e) { // React pools events, so we read the value before debounce. // Alternately we could call `event.persist()` and pass the entire event. // For more info see reactjs.org/docs/events.html#event-pooling this.emitChangeDebounced(e.target.value); } emitChange(value) { this.props.onChange(value); } }
參考this