React:Event Listener

    技术2022-07-10  96

    EventListener

    button中传入onClick;

    <button onClick={this.switchNameHandler}>Switch Name</button>

    注意switchNameHandler要用()=>,不然在函数中用this会出现错误;

    import React, { Component } from 'react'; import './App.css'; import Person from './Person/person'; import { render } from '@testing-library/react'; class App extends Component { state ={ persons:[ {name:'Max' , age:28}, {name:'manu' , age:24}, {name:'Snie' , age:26} ] }; switchNameHandler = ()=>{ console.log('Was Click!'); }; render(){ return ( <div className="App"> <h1>Hi i am a React App!</h1> <p>It is working!</p> <button onClick={this.switchNameHandler}>Switch Name</button> <Person name={this.state.persons[0].name} age={this.state.persons[0].age}/> <Person name={this.state.persons[1].name} age={this.state.persons[1].age}>My Hobbies: Racing</Person> <Person name={this.state.persons[2].name} age={this.state.persons[2].age}/> </div> ); } } export default App;

    App中加入function——setState实现对state内容的更改

    switchNameHandler = ()=>{ //console.log('Was Click!'); //Do not do this //this.state.persons[0].name = 'Maximilian'; this.setState({persons:[ {name:'Max1' , age:28}, {name:'manu1' , age:24}, {name:'Snie1' , age:26} ]}) };
    Processed: 0.008, SQL: 9