易百教程

24、如何在 React 中创建事件?

可以创建一个事件如下:

class Display extends React.Component({      
    show(msgEvent) {  
        // code     
    },     
    render() {        
        // Here, we render the div with an onClick prop      
        return (              
          <div onClick={this.show}>Click Me</div>   
        );      
    }  
});

示例:

import React, { Component } from 'react';  
class App extends React.Component {  
    constructor(props) {  
        super(props);  
        this.state = {  
            companyName: ''  
        };  
    }  
    changeText(event) {  
        this.setState({  
            companyName: event.target.value  
        });  
    }  
    render() {  
        return (  
            <div>  
                <h2>Simple Event Example</h2>  
                <label htmlFor="name">Enter company name: </label>  
                <input type="text" id="companyName" onChange={this.changeText.bind(this)}/>  
                <h4>You entered: { this.state.companyName }</h4>  
            </div>  
        );  
    }  
}  
export default App;