Can anyone tell me how do we know when we need to pass the parameter & when not? For example in below code click={() => this.deletePersonHandler(index)
I am not passing any parameter & directly giving the index argument still the code is working. On the other hand changed={(event) => this.nameChangedHandler(event, person.id)
I have to pass event parameter to make the code work. Here I am getting confuse how to decide when to pass parameter & when not.
import './App.css';
import Person from './Person/Person';
class App extends React.Component {
state = {
persons: [
{ id: 'user1', name: 'Royal1', age: 20},
{ id: 'user2', name: 'Royal2', age: 21},
{ id: 'user3', name: 'Royal3', age: 23}
],
other: 'some other value',
showPersons: false
}
nameChangedHandler = (event, id) => {
const personIndex = this.state.persons.findIndex(p => {
return p.id === id;
})
const person = {
...this.state.persons[personIndex]
}
person.name = event.target.value
const persons = [...this.state.persons]
persons[personIndex] = person
this.setState({ persons: persons})
}
deletePersonHandler = (personIndex) => {
const persons = [...this.state.persons];
persons.splice(personIndex, 1);
this.setState({persons: persons})
}
togglePersonsHandler = () => {
const doesShow = this.state.showPersons;
this.setState({showPersons: !doesShow});
}
render() {
const style = {
backgroundColor: 'pink',
font: 'inherit',
border: '1px solid blue',
cursor: 'pointer'
}
let persons = null;
if (this.state.showPersons) {
persons = <div>
{this.state.persons.map((person, index) => {
return <Person
click={() => this.deletePersonHandler(index)}
name={person.name}
age={person.age}
key={person.id}
changed={(event) => this.nameChangedHandler(event, person.id)} />
})}
</div>
}
return (
<div className="App">
<h1>Hi I am React App</h1>
<p>This is really working!</p>
<button style={style} onClick={this.togglePersonsHandler}>Switch Name</button>
{persons}
</div>
);
}
}
export default App;```
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…