简体   繁体   中英

Inline arrow functions | Empty arguments

I am new to ReactJS and have a question regarding usage of inline arrow functions and unable to understand this even after multiple hours of reading JavaScript ES6 arrow function with ReactJS.

const PersonInputs = ({ idx}) => {
 return (
       <div key={`name-${idx}`}>
      <input type="button" value="Remove Person" onClick={() => removePerson(idx)}/>
       </div>
    );
};

This is my removePerson function defined in a seperate js file:

 const removePerson = (index) => {
        let updatedPersons = [...personState];
        var temp = updatedPersons[index];
         updatedPersons = updatedPersons.filter(person => person.name !== temp.name);
         setPersonState(updatedPersons);
    };

  const blankPerson = { name: '', age: '' };
    const [personState, setPersonState] = useState([
        { ...blankPerson },
    ]);

removePerson function requires index as argument, however when i provide as below i get TypeError: temp is undefined.

const PersonInputs = ({ idx}) => {
 return (
       <div key={`name-${idx}`}>
      <input type="button" value="Remove Person" onClick={(idx) => removePerson(idx)}/>
       </div>
    );
};

I am not able to understand why onClick={(idx) => removePerson(idx)} this causes error, but works with onClick={(idx) => removePerson(idx)}. Can someone please help me on this. Thanks in advance.

onClick passes a synthetic event, not the index. Remove idx as the onClick param:

const PersonInputs = ({ idx}) => {
 return (
       <div key={`name-${idx}`}>
      <input type="button" value="Remove Person" onClick={() => removePerson(idx)}/>
       </div>
    );
}

Since your function is getting React's synthetic event vs your index, it's tossing a type error as a result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM