我想仅当条件为真时才在我的元素上添加 onFocus
事件处理程序。现在,我希望能够对 onFocus
本身进行三元运算,所以像这样:
<input
type='text'
className='some-class'
value={value}
onFocus={useTheOnFocus ? evt => onFocusHandler(evt) : null}
onChange={evt => onChangeHandler(evt.target.value)}
/>
但是,这不起作用并会生成一系列错误和警告:
Uncaught TypeError: handler.apply is not a function
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
我知道另一种方法是在其自己的三元标记中写入两次输入标记,其中一个带有 onFocus
,另一个不带它。但我想以更简洁的方式来做这件事。是否有另一种更简单、更简洁的方法来完成此任务?
最佳答案
你可以添加这个
onFocus={useTheOnFocus ? onFocusHandler : undefined}
或设置一个处理程序
onFocus={onFocusHandler}
并检查处理程序中的条件
onFocusHandler = (ev) => {
if(!condition) {
return null;
}
// your code
}
关于javascript - 我可以仅在某些条件下添加 React 输入事件处理程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51384780/