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;