ReactJS 事件

在本章中,我們將學(xué)習(xí)如何使用事件。

簡單的例子

這是一個簡單的示例,其中我們將只使用一個組件。我們只是添加了onClick事件,updateState一旦單擊按鈕,該事件將觸發(fā)功能。

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState() {
      this.setState({data: 'Data updated...'})
   }
   render() {
      return (
         <div>
            <button onClick = {this.updateState}>CLICK</button>
            <h4>{this.state.data}</h4>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

這將產(chǎn)生以下結(jié)果。

反應(yīng)事件簡單

兒童活動

當(dāng)我們需要state從其子級中更新父級組件時,可以在父級組件中創(chuàng)建一個事件處理程序(updateState),并將其作為prop(updateStateProp)傳遞給子級組件,在這里我們可以對其進(jìn)行調(diào)用。

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         data: 'Initial data...'
      }
      this.updateState = this.updateState.bind(this);
   };
   updateState() {
      this.setState({data: 'Data updated from the child component...'})
   }
   render() {
      return (
         <div>
            <Content myDataProp = {this.state.data} 
               updateStateProp = {this.updateState}></Content>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <button onClick = {this.props.updateStateProp}>CLICK</button>
            <h3>{this.props.myDataProp}</h3>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

這將產(chǎn)生以下結(jié)果。

反應(yīng)事件孩子

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清