在 React 组件中设置条件 onClick 行为 [英] Setting conditional onClick behaviour in React Component
问题描述
我正在开发一个组件,其中一个按钮(提交"类型的输入字段)将在点击后提交数据.但是,我想引入一种保护措施,以便在输入字段为空时在屏幕上显示警报.
I'm working on a component where a button (input field of type 'submit') will submitting data once clicked. However, I'd like to introduce a safeguard to show an alert on screen if the input field is blank.
认为这与组件属性的工作方式相同,我尝试了以下变体,但运气不佳:
Thinking this would work the same way as it would for component attributes, I've tried variations on the following without much luck:
onClick={props.inputText === ''
?
alert("Text cannot be blank.")
:
(e => props.onSubmit(props.inputText))}/>
我宁愿不在 onSubmit 函数内运行检查,以便尽可能隔离对商店的更新(我遵循的是 React-Redux 结构).
I'd rather not run the check inside the onSubmit function in order to isolate updates to the store as far as possible (I'm following a React-Redux structure).
知道 JSX 是否以及如何处理这样的情况吗?
Any idea if and how JSX handles a situation like this?
推荐答案
这应该有效:
onClick={() => { props.inputText === '' ?
alert("Text cannot be blank.") :
props.onSubmit(props.inputText) }}
这篇关于在 React 组件中设置条件 onClick 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!