【发布时间】:2020-04-03 16:46:11
【问题描述】:
在反应中, 什么时候在 Props 中使用函数?
例如在下面的代码中,有时你不会在 prop 中使用函数, 但有时你会这样做。
import React, { useState } from 'react';
const IterationSample = () => {
const input = React.createRef();
const [names, setNames] = useState(
[
{ id: 1, text: 'John' },
{ id: 2, text: 'Jake' },
{ id: 3, text: 'JJ' },
{ id: 4, text: 'Jesus' }
])
const [inputText, setInputText] = useState('');
const [nextId, setNextId] = useState(5);
const onChange = e => setInputText(e.target.value);
const onRemove = id => {
const nextNames = names.filter(name => name.id !== id);
setNames(nextNames);
}
const namesList = names.map(name => <li key={name.id} onDoubleClick={() => onRemove(name.id)}>{name.text}</li>);
const onClick = () => {
const nextNames = names.concat({
id: nextId,
text: inputText
});
setNextId(nextId + 1);
setNames(nextNames);
setInputText('');
input.current.focus();
}
const onEnter = (e) => {
if (e.key === 'Enter') {
onClick();
}
}
return (
<>
<input ref={input} value={inputText} onChange={onChange} onKeyPress={onEnter} />
<button onClick={onClick} >Add</button>
<ul>{namesList}</ul>
</>
);
};
export default IterationSample;
这里你使用 ()=> onDoubleClick={() => onRemove(name.id) 中的一个函数
但是,onKeyPress={onEnter} 或 onChange={onChange} 中都没有
那么什么时候在 props 中使用函数呢?
【问题讨论】:
-
在
onDoubleClick={() => onRemove(name.id)中,您将自定义变量传递给函数。当您只使用函数名称时,您无法传递自定义变量。只有回调传递的变量才会发送到函数。在您的示例中,回调事件将被发送到 onChange 等等。 -
看看这个question
标签: javascript reactjs