为什么我的spread运算符返回一个SyntaxError:Unexpected Token?

时间:2018-02-12 19:56:57

标签: javascript reactjs

这段代码告诉我我在onInputBlur函数中使用setState的扩展运算符。这种语法不正确吗?我在其他组件中使用相同的语法,没有任何问题。这是一个简单的语法问题,还是你怀疑它与更大的问题有关?

感谢。

import React from 'react';

class StateSelect extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      inputCSS: this.props.styles.input || {}
    }


    this.onInputBlur = this.onInputBlur.bind(this)
  }

  onInputBlur = (event) => {
    let choice = event.target.value
    const { styles } = this.props

    if(choice){
      return this.setState(state=> {
        inputCSS: {
          ...state.inputCSS,
          border: '1px solid green'
        }
      })
    } else {
      return this.setState(state=> {
        inputCSS: {
          ...state.inputCSS,
          border: '1px solid red'
        }
      })
    }

  }

  render() {
    const { styles } = this.props
    return (
       <div style={styles.formInput}>
        <select id="state" name="state" onChange={this.props.saveInputVal} onBlur={this.onInputBlur} style={this.state.inputCSS}>
      <option value disabled selected>State</option>
      {Object.keys(States).map((key) => {
        return ( <option key={key} value={key}>{States[key]}</option> )
      })}
    </select>
  </div>
)
}
}

1 个答案:

答案 0 :(得分:2)

问题不在于扩展语法。如果要从arrow函数返回一个对象,则必须将其包含在()括号中。

  return this.setState(state=> ({
    inputCSS: {
      ...state.inputCSS,
      border: '1px solid green'
    }
  }))