Используя Vazco Uniforms в React-Meteor, невозможно получить значение SelectField onChange - PullRequest
0 голосов
/ 16 июня 2019

Рефакторинг формы ReactJS для работы с Vazco-Uniforms. Ошибка получения при выполнении SelectField onChange метода:

Uncaught TypeError: Cannot read property 'value' of undefined @ onConditionChange(event) {
    this.setState({condition: event.target.value});

Нет ошибок при обработке формы в нативном Reactjs

import React from 'react';
import { Stuffs, StuffSchema } from '/imports/api/stuff/stuff';
import { Grid, Segment, Header } from 'semantic-ui-react';
import AutoForm from 'uniforms-semantic/AutoForm';
import TextField from 'uniforms-semantic/TextField';
import NumField from 'uniforms-semantic/NumField';
import SelectField from 'uniforms-semantic/SelectField';
import SubmitField from 'uniforms-semantic/SubmitField';
import HiddenField from 'uniforms-semantic/HiddenField';
import ErrorsField from 'uniforms-semantic/ErrorsField';
import { Bert } from 'meteor/themeteorchef:bert';
import { Meteor } from 'meteor/meteor';

class AddStuff extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      condition: ''
    };

    this.condition = React.createRef();

    this.submit = this.submit.bind(this);
    this.insertCallback = this.insertCallback.bind(this);
    this.formRef = null;

  }

  insertCallback(error) {
    if (error) {
      Bert.alert({ type: 'danger', message: `Add failed: ${error.message}` });
    } else {
      Bert.alert({ type: 'success', message: 'Add succeeded' });
      this.formRef.reset();
    }
  }

  submit(data) {
    const { name, quantity, condition } = data;
    const owner = Meteor.user().username;
    Stuffs.insert({ name, quantity, condition, owner }, this.insertCallback);
  }

    onConditionChange(event) {
    this.setState({condition: event.target.value});
    const condition = this.condition.current.value;
    console.log("Condition changed to: " + condition)

    }

  render() {
    return (
        <Grid container centered>
          <Grid.Column>
            <Header as="h2" textAlign="center">Add Stuff</Header>
            <AutoForm ref={(ref) => { this.formRef = ref; }} schema={StuffSchema} onSubmit={this.submit}>
              <Segment>
                <TextField name='name'/>
                <NumField name='quantity' decimal={false}/>
                <SelectField name='condition' ref={this.condition} value={this.state.condition} onChange={this.onConditionChange.bind(this)}/>
                <SubmitField value='Submit'/>
                <ErrorsField/>
                <HiddenField name='owner' value='fakeuser@foo.com'/>
              </Segment>
            </AutoForm>
          </Grid.Column>
        </Grid>
    );
  }
}

export default AddStuff;


import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
import { Tracker } from 'meteor/tracker';

const Stuffs = new Mongo.Collection('stuff');

const StuffSchema = new SimpleSchema({
  name: String,
  quantity: Number,
  owner: String,
  condition: {
    type: String,
    allowedValues: ['excellent', 'good', 'fair', 'poor', 'sucks'],
    defaultValue: 'good',
  },
}, { tracker: Tracker });

Stuffs.attachSchema(StuffSchema);

export { Stuffs, StuffSchema };

Я ожидаю, что результат выбора значения из SelectField name='condition' onChange обновит состояние "condition" с текущим выбором, предоставленным SimpleSchema.

Ответы [ 2 ]

0 голосов
/ 20 июня 2019

onChangeModel работал отлично, захватывая все обновления формы.Я также смог использовать onChange с условиями, заключенными в AutoForm.Re: ссылка на полный поток вопросов и ответов

 <AutoForm
            ref={(ref) => { this.formRef = ref; }}
            schema={StuffSchema}
            onSubmit={this.submit}
            onChange={(key, value) => {
                if (key === 'condition' && value === 'good') {
                    alert("Condition Good")
            } else {
                    alert("Condition Not Good")
                }
                console.log(key, value)} }
        >
0 голосов
/ 17 июня 2019

SelectField не запускает обычное событие onChange с параметром Event, а вместо этого event.target.value:

  <select
    className="ui selection dropdown"
    disabled={disabled}
    id={id}
    name={name}
    onChange={event => onChange(event.target.value)}
    ref={inputRef}
    value={value}
  >

https://github.com/vazco/uniforms/blob/8b1a1a28a85909df13a84f3ec33f7addb854b905/packages/uniforms-semantic/src/SelectField.js#L50

Так что вы должны быть в порядке с:

onConditionChange(value) {
    this.setState({condition: value});
}
...