×
  • 反应– The Complete Guide (incl. 反应Router 4 & Redux)

  • 14 – Handling Events In 反应with Methods

    课程清单

    在上一课中,我们设置了状态,我告诉您,如果我们还没有真正看到它,那将是非常特殊的。现在我们要做的就是在其中管理数据,然后在 App.js 文件。现在让我们看看React中的事件。

    React中的事件

    现在让我们处理单击此按钮的问题,我们可以通过添加 onClick

    src / App.js
    
    ...
    <button onClick={}>Switch Name</button>
    ...
    
    注意:
    In normal javascript and normal HTML it would be onclick with lowercase c. Now in JSX and that is really important it’s onClick with capital C.

    Now typically we want to execute a function of our class or so called method and this is a convention to give this name like the following switchNameHandler the first part switchName is totally up to you but typically use handler here to indicate that this is a method which we are not actively calling but we assigning as an event handler. It’s not required to follow this pattern though so you can name this what ever you want ofcourse as it is a good practice.
    So switchNameHandler now should b a function, to create a function we will use the ES6 arrow function

    src / App.js
    
    ...
    switchNameHandler = () => {
    	alert('it clicked');
    }
    ...
    

    现在,我想在此之前编辑状态,看看是否可以通过添加点击事件警报来成功调用该状态,
    Now will add that method to click listener and bewween curly braces we can run that function (switchNameHandler).

    src / App.js
    
    ...
    <button onClick={this.switchNameHandler}>Switch Name</button>
    ...
    
    注意
    Dont use function with parentheses e.g. [this.switchNameHandler()]. it will execuate immediately once 反应renders this to the dom because we execuate switchNameHandler() function with the parenthesis.

    We only want to pass a refrence and we do this by using this and then referring to that property which holds a function.

    注意
    if you don’t use the ES6 arrow function syntax where we assign a function to a property you could say, we will run into errors if you try to use this as we will soon do in that function. Because this will not refer to the class at runtime.

    通过使用此ES6语法,我们将找到解决该问题的方法,该问题稍后将变得很重要。
    现在只需保存该文件并在浏览器中打开,然后单击按钮即可在单击开关名称按钮时查看警报。

    完整代码 src / App.js
    
    import React, { Component } from 'react';
    import './App.css';
    import Person from './Person/Person';
    class App extends Component {
    	state = {
    		persons: [{ name: 'Lucy', age: 23 }, { name: 'Max', age: 12 }, { name: 'Mike', age: 34 }],
    	};
    
    	switchNameHandler = () => {
    		alert('called');
    	};
    	render() {
    		return (
    			<div className="App">
    				<h1> Heading</h1>
    				<button onClick={this.switchNameHandler}>Switch Name</button>
    				<Person name={this.state.persons[0].name} age={this.state.persons[0].age} />
    				{/* goes on */}
    			</div>
    		);
    	}
    }
    export 默认 App;
    

    在下一课中,我们将看到如何更改状态。

    反应introduction
    反应Component
    React中的事件
  • 启用通知    不用了,谢谢