ant-design/components/checkbox/demo/controller.md

61 lines
1.3 KiB
Markdown
Raw Normal View History

2016-03-31 09:40:55 +08:00
---
order: 2
2016-08-18 11:22:55 +08:00
title:
2019-05-07 14:57:32 +08:00
zh-CN: 受控的 Checkbox
en-US: Controlled Checkbox
2016-03-31 09:40:55 +08:00
---
2015-07-15 15:19:24 +08:00
2016-08-18 11:22:55 +08:00
## zh-CN
2015-07-15 15:19:24 +08:00
联动 checkbox。
2016-08-18 11:22:55 +08:00
## en-US
Communicated with other components.
```tsx
2022-05-21 22:14:15 +08:00
import { Button, Checkbox } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import React, { useState } from 'react';
2015-07-15 15:19:24 +08:00
const App: React.FC = () => {
const [checked, setChecked] = useState(true);
const [disabled, setDisabled] = useState(false);
2018-06-27 15:55:04 +08:00
const toggleChecked = () => {
setChecked(!checked);
2019-05-07 14:57:32 +08:00
};
2018-11-28 15:00:03 +08:00
const toggleDisable = () => {
setDisabled(!disabled);
2019-05-07 14:57:32 +08:00
};
2018-11-28 15:00:03 +08:00
const onChange = (e: CheckboxChangeEvent) => {
2018-11-28 15:00:03 +08:00
console.log('checked = ', e.target.checked);
setChecked(e.target.checked);
2019-05-07 14:57:32 +08:00
};
2018-11-28 15:00:03 +08:00
const label = `${checked ? 'Checked' : 'Unchecked'}-${disabled ? 'Disabled' : 'Enabled'}`;
return (
<>
<p style={{ marginBottom: '20px' }}>
<Checkbox checked={checked} disabled={disabled} onChange={onChange}>
{label}
</Checkbox>
</p>
<p>
<Button type="primary" size="small" onClick={toggleChecked}>
{!checked ? 'Check' : 'Uncheck'}
</Button>
<Button style={{ margin: '0 10px' }} type="primary" size="small" onClick={toggleDisable}>
{!disabled ? 'Disable' : 'Enable'}
</Button>
</p>
</>
);
};
export default App;
2019-05-07 14:57:32 +08:00
```