变量替换解析错误(意外令牌,预期为“ ...”)

时间:2019-01-04 22:00:49

标签: javascript reactjs material-ui jsx create-react-app

我有一些代码可以动态调整文本字段。

此版本的代码 可以正常运行

  if (props.responsetxt === null) {
    txtField = (
      <TextField
        autoFocus
        margin="dense"
        id="name"
        label={emailField}
        type="email"
        fullWidth
        onChange={e => emailFieldUpdate(e)}
      />
    );

但是我正在使用material-ui,但我想利用其error选项(https://material-ui.com/demos/text-fields/

但是,如果我如下修改我的代码:

let errorFlag = null;  // add this
    txtField = (
      <TextField
        {errorFlag} // add this
        autoFocus
        margin="dense"
        id="name"
        label={emailField}
        type="email"
        fullWidth
        onChange={e => emailFieldUpdate(e)}
      />
    );

我得到一个错误:

  

解析错误:意外的令牌,预期为“ ...”

  Line 45:  Parsing error: Unexpected token, expected "..."

  43 |     txtField = (
  44 |       <TextField
> 45 |         {errorFlag}
     |          ^
  46 |         autoFocus
  47 |         margin="dense"
  48 |         id="name"

我不明白为什么labelonChange动态参数可以正常工作,但是{errorFlag}替换不能吗?

更新

function DownloadForm(props) {
  const intl = props.intl;
  const boxTitle = intl.formatMessage({ id: 'downloadRequest.title' });
  const cancelButton = intl.formatMessage({ id: 'button.cancel' });
  const closeButton = intl.formatMessage({ id: 'button.close' });
  const downloadButton = intl.formatMessage({ id: 'button.download' });
  const emailField = intl.formatMessage({ id: 'downloadRequest.emailField' });
  let boxText = null;
  let waitingAnimation = null;
  let returnArr = {};
  let errorFlag = null;
  const emailFieldUpdate = e => {
    returnArr['email'] = e.target.value;
    if (!EmailValidator(e.target.value)) {
        console.log('setting true !');
        errorFlag=true;
    }
  };
  returnArr['subset'] = props.selectedSubset;
  if (props.showWaitingAnimation) {
    waitingAnimation = <CircularProgress />;
  }
  if (props.responsetxt === null) {
    returnArr['correlID'] = UUIDGenerator();
    returnArr['boxOpened'] = TAI64.now().toHexString();
    boxText = intl.formatMessage({ id: 'downloadRequest.prompt' });
  } else {
    boxText = props.responsetxt;
}
  let txtField, submitButton, closeText;
  if (props.responsetxt === null) {
    txtField = (
      <TextField
        error={errorFlag}
        autoFocus
        margin="dense"
        id="name"
        label={emailField}
        type="email"
        fullWidth
        onChange={e => emailFieldUpdate(e)}
      />
    );
    submitButton = (
      <Button
        color="primary"
        onClick={() =>
          props.submit(returnArr, process.env.REACT_APP_ITS_AWS_SQS_DOWNLOAD)
        }
      >
        {downloadButton}
      </Button>
    );
    closeText = cancelButton;
  } else {
    closeText = closeButton;
  }
  return (
    <div>
   <Dialog open={props.open} aria-labelledby="form-dialog-title">
        <DialogTitle id="form-dialog-title">{boxTitle}</DialogTitle>
        <DialogContent>
          <DialogContentText>{boxText}</DialogContentText>
          {waitingAnimation}
          {txtField}
        </DialogContent>
        <DialogActions>
          <Button color="primary" onClick={props.close}>
            {closeText}
          </Button>
          {submitButton}
        </DialogActions>
      </Dialog>
    </div>
  );
}
export default injectIntl(DownloadForm);

1 个答案:

答案 0 :(得分:1)

从文档中:

  <TextField
      error
      id="standard-error"
      label="Error"
      defaultValue="Hello World"
      className={classes.textField}
      margin="normal"
  />

这里的errorerror={true}的简短语法,无法动态复制。 但是,您可以执行以下操作:

  <TextField
    error={errorFlag}
    autoFocus
    margin="dense"
    id="name"
    label={emailField}
    type="email"
    fullWidth
    onChange={e => emailFieldUpdate(e)}
  />

并且正如您的错误消息所告诉您的那样,解构单个属性JSON也可能有效:

  <TextField
    ...{error : errorFlag}

将其重命名为error将进一步减少语法:

  <TextField
    ...{error}

编辑:

您正在使用无状态React组件,这意味着它永远不会自行重新渲染,并且调用emailFieldUpdate也不会。我将您的组件重构为有状态的组件,其中errorFlag处于您的状态。

调用this.setState({ errorFlag: true })将更新您的标志并重新渲染组件,向您显示错误。我还做了一些代码可读性更改:

import React, { Component } from 'react'
export default class DownloadForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
            errorFlag: null,
            returnArr: {}
        }
    }

    emailFieldUpdate = e => {
        this.setState({ returnArr:{ email: e.target.value }})
        if (!EmailValidator(e.target.value)) {
            console.log('setting true !');
            this.setState({ errorFlag: true })
        }
    };

    render() {
        const { selectedSubset, responsetxt, showWaitingAnimation, intl, submit, open, close } = this.props //Decontructs your props
        const { errorFlag, returnArr } = this.state //Deconstructs your state

        const [boxTitle, cancelButton, closeButton, downloadButton, emailField] = 
        ['downloadRequest.title', 'button.cancel', 'button.close', 'button.download', 'downloadRequest.emailField'].map(id =>
            intl.formatMessage({ id })
        );
        let boxText = null;
        let waitingAnimation = null;

        returnArr['subset'] = selectedSubset;
        if (showWaitingAnimation) {
            waitingAnimation = <CircularProgress />;
        }
        if (!responsetxt) {
            returnArr['correlID'] = UUIDGenerator();
            returnArr['boxOpened'] = TAI64.now().toHexString();
            boxText = intl.formatMessage({ id: 'downloadRequest.prompt' });
        } else {
            boxText = responsetxt;
        }
        return (
            <div>
                <Dialog open={open} aria-labelledby="form-dialog-title">
                    <DialogTitle id="form-dialog-title">{boxTitle}</DialogTitle>
                    <DialogContent>
                        <DialogContentText>{boxText}</DialogContentText>
                        {waitingAnimation}
                        {!responsetxt && 
                            <TextField
                                error={errorFlag}
                                autoFocus
                                margin="dense"
                                id="name"
                                label={emailField}
                                type="email"
                                fullWidth
                                onChange={this.emailFieldUpdate}
                            />
                        }
                    </DialogContent>
                    <DialogActions>
                        <Button color="primary" onClick={close}>
                            {responsetxt ? closeButton : cancelButton}
                        </Button>
                        {!responsetxt && 
                            <Button
                                color="primary"
                                onClick={() => {submit(returnArr, process.env.REACT_APP_ITS_AWS_SQS_DOWNLOAD)}}>
                                {downloadButton}
                            </Button>
                        }
                    </DialogActions>
                </Dialog>
            </div>
        );
    }
}

您似乎正在使用React-intl,请查看此文档以将消息直接发送到JSX中:https://github.com/yahoo/react-intl/wiki/Components#formattedmessage

我也建议阅读conditional rendering in Reactdeconstruction in JS