据我所知,在 JavaScript 中有三种定义函数的方法。
<强>1。声明
function handleEvent(e) {}
<强>2。作业
var handleEvent = function(e) {}
<强>3。箭头
var handleEvent = (e) => {}
我花了好几个小时试图找到有关这些选项中哪些是在功能性 React 组件中声明处理程序的首选方式的信息。我找到的所有文章都在谈论类组件、绑定(bind)等。但是有了新的 Hooks out,在函数内部也必须有定义它们的标准。 (毕竟,函数式组件本来就是存在的。)
考虑以下组件,它声明了三个处理程序,它们是您在 React 组件中可能需要的不同行为的示例。
function NameForm(props) {
const [inputName, setInputName] = useState("");
useEffect(() => setInputName(props.initialValue), [props.initialValue]);
const handleInputChange = function(event) {
setInputName(event.target.value);
};
const resetForm = function() {
setInputName(props.initialValue);
props.onReset();
};
const handleFormSubmit = function(event) {
event.preventDefault();
props.onSubmit(inputName);
resetForm();
};
/* React-Bootstrap simple form example using these handlers. */
return (
<Form onSubmit={handleFormSubmit}>
<Form.Group controlId="NameForm">
<Form.Control
type="text"
placeholder="Enter your name here"
value={inputName}
onChange={handleInputChange}
/>
<Button type="submit">Submit</Button>
<Button onClick={resetForm}>Reset</Button>
</Form.Group>
</Form>
);
}
所有这些处理程序都作为回调直接传递给其他组件。它们可能会在任何时候被调用,但在那一刻,我们需要访问 props
的当前值和任何状态,如 输入名称
。此外,您可能已经注意到,handleFormSubmit
处理程序还会调用 resetForm
处理程序。
从性能 Angular 定义处理程序的推荐方法是什么?是否可以避免在每次渲染时重新定义它们?
useCallback
是否也适合这里的某处?
最佳答案
当前的标准是将处理程序声明为不变性常量和用于绑定(bind)目的的箭头函数。
function NameForm(props) {
const [inputName, setInputName] = useState("");
useEffect(() => setInputName(props.initialValue), [props.initialValue]);
const handleInputChange = (event) => {
setInputName(event.target.value);
}
const resetForm = () => {
setInputName(props.initialValue);
props.onReset();
}
const handleFormSubmit = (event) => {
event.preventDefault();
props.onSubmit(inputName);
resetForm();
}
/* React-Bootstrap simple form example using these handlers. */
return (
<Form onSubmit={handleFormSubmit}>
<Form.Group controlId="NameForm">
<Form.Control
type="text"
placeholder="Enter your name here"
value={inputName}
onChange={handleInputChange}
/>
<Button type="submit">Submit</Button>
<Button onClick={resetForm}>Reset</Button>
</Form.Group>
</Form>
);
}
All of these handlers are directly passed as callbacks into other components. They might be called whenever, but at that exact moment, we need to have access to the current values of props and any state like inputName
按照目前的构造,我们符合您描述的要求。由于 props
和 state
被定义为组件可以访问的更高级别的数据,因此所有事件处理程序都可以访问它们。当在另一个组件中用作回调时,它们将保持绑定(bind)到定义它们的初始组件。
这意味着如果您有这样的事件处理程序:
const handleInputChange = (e) => {
setValue(e.target.value)
}
然后像这样将它传递给 ChildComponent:
<Child handleInputChange={handleInputChange}/>
Child 像这样使用 prop/event-handler:
<input onChange={props.handleInputChange}/>
您将从 Child 输入获取 event
,但您将更新 Parent 的 state
,即定义事件处理程序的原始组件。
关于javascript - 在功能性 React 组件中定义处理程序的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57337030/