从 @fluentui/react-northstar@0.48.0 中读取表单组件



在fluentui 上有一个漂亮的基于模式的表单组件

import React from 'react';
import { Form, Button } from '@fluentui/react-northstar';
const fields = [
{
label: 'First name',
name: 'firstName',
id: 'first-name-shorthand',
key: 'first-name',
required: true,
},
{
label: 'Last name',
name: 'lastName',
id: 'last-name-shorthand',
key: 'last-name',
required: true,
},
{
label: 'I agree to the Terms and Conditions',
control: {
as: 'input',
},
type: 'checkbox',
id: 'conditions-shorthand',
key: 'conditions',
},
{
control: {
as: Button,
content: 'Submit',
},
key: 'submit',
},
];
const FormExample = () => (
<Form
onSubmit={() => {
alert('Form submitted');
}}
fields={fields}
/>
);
export default FormExample;

但是他们没有提供任何方法/示例来收集我能说的数据。(至少在文档中没有(。 我可以从onSubmit事件中收集大多数值,但它变得很麻烦,因为并非所有 html 组件都一定是具有value属性的输入元素。我也不认为这是预期的方式。请问任何人都可以启发我吗?我认为您必须能够以某种方式将onChange功能提供给它。还是我应该在每个字段对象中添加onChange函数?

我最终梳理了库组件(表单输入和复选框(,看看是什么让它们打勾。

这就是我最终得到的。如果将来有其他人偶然发现这一点,请随时改进它。

请注意,使用属性defaultValuedefaultChecked分别设置输入和复选框组件的初始值。以及传递输入组件的namevalue参数以及复选框组件的namecheckedonChange事件。

如果您希望复选框标签显示在复选框旁边,则必须位于控件内部,否则它将显示在复选框上方。

import React, { Component } from 'react';
import { Form, Button, Checkbox, Input } from '@fluentui/react-northstar';
class Login extends Component {
constructor(props) {
super(props);
this.handleSubmit.bind(this)
}
state = {
email: "",
password: "",
remember_me: true
}
fields = [
{
label: 'Email',
name: 'email',
id: 'email-inline-shorthand',
key: 'email',
required: true,
inline: true,
type: 'email',
control: {
as: Input,
defaultValue: this.state.email,
onChange: (e, { name, value }) => this.setState({ ...this.state, [name]: value })
}
},
{
label: 'Password',
name: 'password',
id: 'password-inline-shorthand',
key: 'password',
required: true,
inline: true,
type: 'password',
control: {
defaultValue: this.state.password,
onChange: (e, { name, value }) => this.setState({ ...this.state, [name]: value }),
as: Input,
}
},
{
name: "remember_me",
key: 'remember_me',
id: 'remember_me-inline-shorthand',
type: 'boolean',
control: {
label: 'Remember me',
as: Checkbox,
defaultChecked: !!this.state.remember_me,
onChange: (e, { name, checked }) => { this.setState({ ...this.state, [name]: checked }) }
},
},
{
control: {
as: Button,
content: 'Submit',
},
key: 'submit',
},
]
handleSubmit = (e) => {
console.log("submitting these values", this.state)
}
render() {
return (
<Form
onSubmit={this.handleSubmit}
fields={this.fields}
/>
)
}
};
export default Login;

最新更新