英文:
How can I have an antd checkbox checked when its value is falsy inside an antd formItem?
问题
目前,我想要做的是“反转” antd 复选框组件的行为。当 antD formItem
的 value
/ initialValue
为 false
时,我想要复选框未选中。这是我的当前代码:
<FormItem
label="在搜索中包括技能列表"
labelCol={{ span: 24 }}
initialValue={false}
valuePropName="checked"
name="ignoreSkills"
>
<Checkbox value={false} defaultChecked={true}>搜索技能</Checkbox>
</FormItem>
如果复选框在 formItem
外部,设置 defaultChecked={true}
将有效,但当它在内部时,一切都会出问题。
我尝试过的方法:
- 仅使用
defaultChecked={true}
。在formItem
内部不起作用。 - 使用
checked={true}
属性。在formItem
内部不起作用。
有没有办法在 antd 的 formItem
内部实现这一点?
英文:
Currently, what I would like to do is "inverse" the behavior of the antd checkbox component. I want to have the checkbox unchecked when the value
/ initialValue
of the antD formItem
is false
. This is my current code
<FormItem
label="Include skills list in the search"
labelCol={{ span: 24 }}
initialValue={false}
valuePropName="checked"
name="ignoreSkills"
>
<Checkbox value={false} defaultChecked={true}>Search on Skills</Checkbox>
</FormItem>
Setting the defaultChecked={true}
works fine if the checkbox is OUTSIDE the formItem
but when it's inside, everything just breaks.
Things I tried:
- Using the
defaultChecked={true}
alone. Doesn't work inside formItem - Using the
checked={true}
property. Doesn't work insideformItem
Any idea how I can achieve this inside the antd formItem
?
答案1
得分: 1
你可以使用 getValueProps
和 getValueFromEvent
属性来实现相反的行为。getValueFromEvent
函数提供了从特定事件中提取值的自定义处理程序,例如对于复选框,我们需要从 e.target.checked
中获取值。因此,我们传递 valuePropName="checked"
。你可以使用此函数来反转复选框的值。使用 getValueProps
,你可以定义如何从属性中获取值。
英文:
You can use getValueProps
& getValueFromEvent
prop to achieve inverse behaviour. getValueFromEvent
function provides a custom handler how to extract value from a particular event i.e. for checkbox we need to get value form e.target.checked
. So we pass valuePropName="checked"
. You can inverse the value of checkbox using this function. Using getValueProps
, you can define how to get value from props.
import { Checkbox, Form } from 'antd';
const App = () => {
return (
<Form>
<Form.Item
label='Include skills list in the search'
labelCol={{ span: 24 }}
valuePropName='checked'
name='ignoreSkills'
getValueProps={(value) => ({ checked: !value })}
getValueFromEvent={(e) => !e.target.checked}
>
<Checkbox>Search on Skills</Checkbox>
</Form.Item>
</Form>
);
};
export default App;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论