ant-design/components/mention/demo/controlled.md

85 lines
2.1 KiB
Markdown
Raw Normal View History

---
order: 4
2016-09-23 10:14:57 +08:00
title:
zh-CN: 配合 Form 使用
en-US: With Form
---
## zh-CN
受控模式,例如配合 Form 使用。
## en-US
Controlled mode, for example, to work with `Form`.
2017-02-13 10:55:53 +08:00
````jsx
import { Mention, Form, Button } from 'antd';
const { toEditorState, getMentions } = Mention;
const FormItem = Form.Item;
class App extends React.Component {
2017-02-20 21:47:57 +08:00
state = {
initValue: toEditorState('@afc163'),
}
handleReset = (e) => {
e.preventDefault();
this.props.form.resetFields();
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((errors, values) => {
2016-08-23 21:00:35 +08:00
if (errors) {
console.log('Errors in form!!!');
return;
}
console.log('Submit!!!');
console.log(values);
});
}
checkMention = (rule, value, callback) => {
const { getFieldValue } = this.props.form;
const mentions = getMentions(getFieldValue('mention'));
if (mentions.length < 2) {
callback(new Error('More than one must be selected!'));
} else {
callback();
}
}
render() {
const { getFieldDecorator, getFieldValue } = this.props.form;
console.log('>> render', getFieldValue('mention') === this.state.initValue);
2016-07-21 15:40:13 +08:00
return (
2017-03-06 17:51:45 +08:00
<Form layout="horizontal">
2016-07-21 15:40:13 +08:00
<FormItem
id="control-mention"
label="Top coders"
2016-07-21 15:40:13 +08:00
labelCol={{ span: 6 }}
wrapperCol={{ span: 14 }}
>
{getFieldDecorator('mention', {
rules: [
{ validator: this.checkMention },
],
initialValue: this.state.initValue,
})(
<Mention
suggestions={['afc163', 'benjycui', 'yiminghe', 'RaoHai', '中文', 'にほんご']}
/>
)}
2016-07-21 15:53:33 +08:00
</FormItem>
2016-07-21 15:40:13 +08:00
<FormItem wrapperCol={{ span: 14, offset: 6 }}>
<Button type="primary" onClick={this.handleSubmit}>Submit</Button>
2016-07-21 15:40:13 +08:00
&nbsp;&nbsp;&nbsp;
2017-02-04 22:35:33 +08:00
<Button onClick={this.handleReset}>Reset</Button>
2016-07-21 15:40:13 +08:00
</FormItem>
</Form>
);
}
}
2017-02-20 21:40:24 +08:00
const FormDemo = Form.create()(App);
2016-07-21 15:40:13 +08:00
2017-02-20 21:40:24 +08:00
ReactDOM.render(<FormDemo />, mountNode);
````