[英]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. 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:这是我在单独的 js 文件中定义的 removePerson function:
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. removePerson function 需要索引作为参数,但是当我提供如下时,我得到 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)}.我无法理解为什么 onClick={(idx) => removePerson(idx)} 这会导致错误,但适用于 onClick={(idx) => removePerson(idx)}。 Can someone please help me on this.有人可以帮我解决这个问题。 Thanks in advance.提前致谢。
onClick
passes a synthetic event, not the index. onClick
通过合成事件,而不是索引。 Remove idx
as the onClick
param:删除idx
作为onClick
参数:
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.由于您的 function 正在获取 React 的合成事件与您的索引,因此它会抛出类型错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.