简体   繁体   English

材质UI文本字段未显示值

[英]Material UI TextField Not Showing Value

I have a form in react where I'm using a Material UI TextField. 我在使用Material UI TextField的地方有一个反应形式。 I want a value present in the TextField and I can see that it is being set when I use the Inspect option of Google Chrome. 我希望在TextField中存在一个值,并且可以看到使用Google Chrome的Inspect选项时正在设置该值。 In addition to that, I see that the type="hidden". 除此之外,我看到type =“ hidden”。 I have changed this to type="text" and to no avail, the value is still not presented. 我将其更改为type =“ text”,但无济于事,该值仍未显示。 Curious if anyone here has any understanding as to why this would happen. 好奇这里是否有人对此会发生什么了解。 Below is the primary code that is causing the problem: 下面是导致该问题的主要代码:

        <TextField
            name="Property"
            select
            fullWidth
            margin="normal"
            className={clsx(selectInputStyle.margin, selectInputStyle.textField, selectInputStyle.root)}
            value={viewProperties[index].name}
            onChange={this.handleSelectChange}
          >
            {propertyKeys.map((key, index) => (
              <MenuItem value={key} key={index}>
                {key}
              </MenuItem>
            ))}
          </TextField>

Here is the full code file just for a complete context of what is going on. 这是完整代码文件,仅用于显示所发生情况的完整上下文。

    import React, { Component } from 'react';
    import { Container, Form, Button, Row, Col, Nav, NavItem, NavLink, Input, FormGroup } from 'reactstrap';
    import { connect } from 'react-redux';
    import { reduxForm, FieldArray, arrayRemoveAll } from 'redux-form/immutable';
    import * as Immutable from 'immutable';
    import _ from 'lodash';
    import { bindActionCreators } from 'redux';
    import BlockUi from 'react-block-ui';
    import MaterialButton from '@material-ui/core/Button';
    import DeleteIcon from '@material-ui/icons/Delete';
    import { makeStyles } from '@material-ui/core/styles';
    import AppBar from '@material-ui/core/AppBar';
    import Tabs from '@material-ui/core/Tabs';
    import Tab from '@material-ui/core/Tab';
    import MenuItem from '@material-ui/core/MenuItem';
    import Select from '@material-ui/core/Select';
    import InputMaterial from '@material-ui/core/Input';
    import FormControl from '@material-ui/core/FormControl';
    import TextField from '@material-ui/core/TextField';
    import OutlinedInput from '@material-ui/core/OutlinedInput';
    import clsx from 'clsx';
    import { AvText, AvSelect } from '../forms/components';
    import { showNotification, loadPayerProperties, updatePayerProperties } from '../actions';

    class PayerPropertiesEditor extends Component {
     constructor(props) {
      super(props);

    this.uploadRef = React.createRef();
    this.state = {
      errors: [],
      refeshProperties: false,
      blocking: false
    };

    this.showButton = false;
    this.divPadding = { padding: '20px' };
    this.doSubmit = this.doSubmit.bind(this);
    this.handleInvalidSubmit = this.handleInvalidSubmit.bind(this);
    this.renderProperties = this.renderProperties.bind(this);
    this.handleSelectChange = this.handleSelectChange.bind(this);

    this.useStyles = makeStyles(theme => ({
      button: {
        margin: theme.spacing(1)
      },
      leftIcon: {
        marginRight: theme.spacing(1)
      },
      rightIcon: {
        marginLeft: theme.spacing(1)
      },
      iconSmall: {
        fontSize: 20
      },
      root: {
        display: 'flex',
        flexWrap: 'wrap'
      },
      formControl: {
        margin: theme.spacing(1),
        minWidth: 120
      },
      selectEmpty: {
        marginTop: theme.spacing(2)
      },
      container: {
        display: 'flex',
        flexWrap: 'wrap'
      },
      input: {
        margin: theme.spacing(1)
      }
    }));
  }

  componentDidMount() {
    this.setState({ view: 'payer' });
  }

  componentDidUpdate(prevProps) {
    const { loadPayerProperties } = this.props;
    if (this.state.refeshProperties) {
      this.props.arrayRemoveAll('payerPropertiesEditorForm', 'properties');
      loadPayerProperties();
      this.setState({ refeshProperties: false });
      this.setState({ blocking: false });
      this.showButton = false;
    }
    if (!prevProps.properties && this.props.properties) {
      this.props.change('properties', Immutable.fromJS(this.props.properties));
    }
  }

  doSubmit(values) {
    const { updatePayerProperties } = this.props;
    return new Promise(resolve => {
      this.setState({
        blocking: true
      });

      updatePayerProperties(values.toJS(), () => {
        this.setState({ refeshProperties: true });
      });

      resolve();
    });
  }

  handleInvalidSubmit() {
    this.props.showNotification({
      level: 'error',
      message: 'Errors were found.'
    });
  }

  handleSelectChange(event) {
    console.log(event);
  }

  renderProperties({ fields }) {
    const inputUseStyles = makeStyles(theme => ({
      root: {
        display: 'flex',
        flexWrap: 'wrap'
      },
      formControl: {
        margin: theme.spacing(1),
        minWidth: 120
      },
      selectEmpty: {
        marginTop: theme.spacing(2)
      },
      container: {
        display: 'flex',
        flexWrap: 'wrap'
      },
      margin: {
        margin: theme.spacing(1)
      },
      textField: {
        flexBasis: 200
      },
      input: {
        margin: theme.spacing(1)
      }
    }));
    const selectInputStyle = inputUseStyles().input;
    const useStyles = this.useStyles();
    const { formProperties, unsetPropertiesKeys } = this.props;
    const viewProperties = formProperties[`${this.state.view}`];
    const propertyKeys = unsetPropertiesKeys[`${this.state.view}`];
    return (
      <div maxWidth="sm" className={selectInputStyle.root}>
        {fields.map((property, index) => (
          <Row
            key={index}
            style={{
              display: viewProperties[index].action === 'remove' ? 'none' : ''
            }}
          >
            <Col xs={5}>
              <TextField
                select
                fullWidth
                margin="normal"
                className={clsx(selectInputStyle.margin, selectInputStyle.textField, selectInputStyle.root)}
                value={viewProperties[index].name}
                onChange={this.handleSelectChange}
              >
                {propertyKeys.map((key, index) => (
                  <MenuItem value={key} key={index}>
                    {key}
                  </MenuItem>
                ))}
              </TextField>
            </Col>
            <Col xs={5}>
              <AvText
                name={`${property}.value`}
                onChange={() => {
                  if (viewProperties[index].action !== 'add') {
                    this.props.change(`${property}.action`, 'update');
                    this.showButton = true;
                  }
                }}
              />
            </Col>
            <Col xs={1}>
              <MaterialButton
                variant="contained"
                className="{classes.button}"
                onClick={() => {
                  fields.remove(index);
                  if (viewProperties[index].action !== 'add') {
                    fields.insert(
                      index,
                      Immutable.fromJS(Object.assign({}, viewProperties[index], { action: 'remove' }))
                    );
                    this.showButton = true;
                  }
                }}
              >
                Delete
                <DeleteIcon className={useStyles.rightIcon} />
              </MaterialButton>
            </Col>
          </Row>
        ))}

        <Row>
          <Col xs={12}>
            <Button
              color="primary"
              onClick={() => {
                fields.push(
                  Immutable.fromJS({
                    owner: this.props.ownerKeys[this.state.view],
                    action: 'add'
                  })
                );
                this.showButton = true;
              }}
            >
              Add Property
            </Button>
          </Col>
        </Row>
        <br />

        {this.showButton === true && (
          <Row>
            <Col xs={12}>
              <Button color="primary" type="submit">
                Submit
              </Button>
            </Col>
          </Row>
        )}
      </div>
    );
  }

  render() {
    const { handleSubmit, properties, payerName, chsId, parentChsId } = this.props;
    const formStyles = makeStyles(theme => ({
      root: {
        display: 'flex',
        flexWrap: 'wrap'
      },
      formControl: {
        margin: theme.spacing(1),
        minWidth: 120
      },
      selectEmpty: {
        marginTop: theme.spacing(2)
      }
    }));

    const navItems = ['payer', 'clearinghouse', 'parent'].map(key => (
      <Tab
        textColor="primary"
        key={key}
        label={
          key === 'payer'
            ? 'PAYER: ' + payerName
            : key === 'clearinghouse'
              ? 'CLEARING HOUSE: ' + chsId
              : 'PARENT: ' + parentChsId
        }
        onClick={() => this.setState({ view: key })}
      />
    ));

    const overrides = this.state.view === 'payer' ? ['clearinghouse'] : this.state.view === 'parent' ? ['parent'] : [];
    const readonly = properties
      ? overrides
          .filter(key => key !== this.state.view)
          .map(key => properties[key])
          .reduce((acc, val) => acc.concat(val), [])
          .map((property, idx) => {
            return (
              <Row key={idx}>
                <Col xs={5}>
                  <FormGroup>
                    <Input value={property.name} disabled />
                  </FormGroup>
                </Col>
                <Col xs={5}>
                  <FormGroup>
                    <Input value={property.value} disabled />
                  </FormGroup>
                </Col>
              </Row>
            );
          })
      : [];
    return (
      <BlockUi tag="div" blocking={this.state.blocking} className="my-2">
        <Container maxWidth="sm">
          <AppBar position="static" color="default">
            <Tabs variant="fullWidth" textColor="primary">
              {navItems}
            </Tabs>
          </AppBar>

          <FormControl
            fullWidth
            className="mt-4"
            onSubmit={handleSubmit(this.doSubmit)}
            ref={form => (this.formRef = form)}
          >
            {readonly}
            <FieldArray
              name={`properties.${this.state.view}`}
              component={this.renderProperties}
              rerenderOnEveryChange
            />
          </FormControl>
        </Container>
      </BlockUi>
    );
  }
}

const mapStateToProps = state => {
  const {
    payerPropertiesStore: {
      payer: { payerId, payerName, chsId, parentChsId },
      properties,
      propertyKeys
    },
    form: {
      payerPropertiesEditorForm: {
        values: { properties: formProperties }
      }
    }
  } = state.toJS();
  const unsetPropertiesKeys = {};
  for (const view of ['payer', 'clearinghouse', 'parent']) {
    unsetPropertiesKeys[view] = propertyKeys.filter(key => !_.find(formProperties[view], { name: key }));
  }
  const ownerKeys = { payer: payerId, clearinghouse: chsId, parent: parentChsId };
  return { formProperties, properties, ownerKeys, unsetPropertiesKeys, payerId, payerName, chsId, parentChsId };
};

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      showNotification,
      loadPayerProperties,
      updatePayerProperties,
      arrayRemoveAll
    },
    dispatch
  );

export default reduxForm({
  form: 'payerPropertiesEditorForm',
  enableReinitialize: true,
  initialValues: Immutable.fromJS({ properties: {} })
})(
  connect(
    mapStateToProps,
    mapDispatchToProps
  )(PayerPropertiesEditor)
);

In the TextField you are setting value from viewProperties like, TextField您可以通过viewProperties设置值,例如,

value={viewProperties[index].name}

You are getting data in viewProperties from formProperties based on this.state.view 您在获取数据viewPropertiesformProperties基于this.state.view

const viewProperties = formProperties[`${this.state.view}`];

As you are setting view state in componentDidMount , on intial render view is not set and don't have value so you are not getting any value from formProperties . 当您在componentDidMount中设置view状态时,初始渲染view未设置且没有值,因此您不会从formProperties获得任何值。

You need to have a default state, 您需要具有默认状态,

this.state = {
   errors: [],
   refeshProperties: false,
   blocking: false,
   view: 'payer' // default set
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM