组件通信
- 父组件向子组件通信:最常用
父组件通过props向子组件传递参数
- 子组件向父组件通信:利用回调函数
父组件将一个函数作为props传递给子组件,子组件调用该回调函数,向父组件通信。
- 跨级组件之间通信:爷孙通信
- 中间组件层层传递props(存在嵌套太深的问题)
- 使用context对象(推荐)
context是全局容器,静态属性,使用条件:
- 父组件要声明自己支持context,并提供context中属性的PropTypes
- 子组件要声明自己需要使用context,并提供需要使用的context中属性的PropTypes
- 父组件需提供一个getChildContext函数,返回一个相应的初始context对象
若组件中使用constructor函数,务必在构造函数中传入第二个参数context,并在super调用父类构造函数时也传入context,否则会造成组件中无法使用context
constructor(props,context){
super(props,context);
}
- 非嵌套组件间通信:
- 利用二者共同父组件的context对象通信(存在嵌套太深、组件耦合度大的问题)
- 使用自定义事件的方式(事件订阅,推荐)
节流
Throttle,阻止函数在给定时间内被多次调用。
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);
}
}
参考