class CommentList extends React.Component { constructor() { super(); this.handleChange = this.handleChange.bind(this); this.state = { // "DataSource" is some global data source comments: DataSource.getComments() }; }
componentDidMount() { // Subscribe to changes DataSource.addChangeListener(this.handleChange); }
componentWillUnmount() { // Clean up listener DataSource.removeChangeListener(this.handleChange); }
handleChange() { // Update component state whenever the data source changes this.setState({ comments: DataSource.getComments() }); }
render() { // ... and renders the wrapped component with the fresh data! // Notice that we pass through any additional props return <WrappedComponent data={this.state.data} {...this.props} />; } }; }
不要改变原始组件,使用合成手段,不要在render方法中使用高阶组件
合成事件
合成事件的属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14
boolean bubbles boolean cancelable DOMEventTarget currentTarget boolean defaultPrevented number eventPhase boolean isTrusted DOMEvent nativeEvent void preventDefault() boolean isDefaultPrevented() void stopPropagation() boolean isPropagationStopped() DOMEventTarget target number timeStamp string type