首页 > 解决方案 > ReactJS - How a property can be setted by an argument following a comma?

问题描述

I work currently on a specific section ReactJS documentation - here the corresponding link : in https://reactjs.org/docs/lifting-state-up.html or on codepen : https://codepen.io/gaearon/pen/WZpxpz?editors=0010#0 .

There is something in the code which interrogate me : How is possible that a value be updated by an argument passed in a function following a coma. Here the example to be more understandable :

 handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

corresponding to :

which handle :

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

How the temperature argument can handle the setting of temperature property, if someone can explain me it would be great.

Kind regard, J.Doe

标签: javascriptpropertiescallbackjsxsetstate

解决方案


This :

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

is equivalent to this : (notice the temperature property)

 handleCelsiusChange(temperature) {
    this.setState({
        scale: 'c', 
        temperature: temperature
    });
  }

Which is equivalent to this :

 handleCelsiusChange(newValue) {
    this.setState({
        scale: 'c', 
        temperature: newValue
    });
  }

The first syntax is the new shorthand form introduced in ES6


推荐阅读