[ReactJS] DOM Event Listeners in a React Component
React in dom Component Event ReactJS
2023-09-14 08:59:20 时间
React doesn't provide the listener to listen the DOM event. But we can do it in React life cycle:
So when the compoment did mount, we add listeners to the dom event.
And remember to remove the dom listener when the compoment unmount.
var Box = React.createClass({ getInitialState:function(){ return { width: window.innerWidth, scroll: document.body.scrollTop }; }, update: function(){ this.setState({ width: window.innerWidth, scroll: document.body.scrollTop }) }, componentDidMount:function(){ window.addEventListener('resize', this.update); widnow.addEventListener('scroll', this.update); }, componentWillUnmount:function(){ window.removeEventListener('resize', this.update); window.removeEventListener('scroll', this.update); }, render:function(){ return <div> <p>width: {this.state.width}</p> <p>scroll: {this.state.scroll}</p> </div>; } }); //React.render will be depricated in the next release //https://facebook.github.io/react/blog/2015/09/10/react-v0.14-rc1.html#two-packages-react-and-react-dom ReactDOM.render(<Box />, document.getElementById('box'));
相关文章
- [React] Handle Recoil Asynchronous Selectors using Loadables in React
- [React Testing] Test Drive Mocking react-router’s Redirect Component on a Form Submission
- [React Testing] Mock HTTP Requests with jest.mock in React Component Tests
- [React] {svg, css module, sass} support in Create React App 2.0
- [React] Understanding setState in componentDidMount to Measure Elements Without Transient UI State
- [React] Define defaultProps and PropTypes as static methods in class component
- [D3] Creating a D3 Force Layout in React
- [React Router v4] Use URL Parameters
- [React] React hook, component props for refactoring
- [React] Using react-styleguidist for Component demo
- [React] Setup an API Proxy in Create React App
- [React Testing] Test react-router-dom Router Provider with createMemoryHistory
- [React] Reference a node using createRef() in React 16.3
- [React] Implement a Higher Order Component with Render Props
- [React Fundamentals] Component Lifecycle - Updating
- [React Fundamentals] Using Refs to Access Components
- [React Native] Build a Github Repositories component
- [React Native] Create a component using ScrollView
- [React Testing] The Redux Store - Multiple Actions
- [React] React Fundamentals: State Basics
- 如何得到React应用转换后的JavaScript代码
- Taro React组件使用(4) —— RuiInputCode 验证码输入框