最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - event.target.value question with React.js - Stack Overflow

programmeradmin2浏览0评论

I'm going through documentation on React.js on this website and came across code that I was confused by.

From what I understand, the prefilled state of the isGoing checkbox will be true (hence checked) whereas the numberOfGuests is 2.

The part I get confused on is the handleInputChange() function which sets the variable target equal to event.target - it's a pre-built attribute that returns the DOM element that triggered the event. The value variable, allows for target.name to retrieve the name and assigns it to target.checked as a truthy and target.value as a falsy. The "target.checked" retrieves the current state of isOnGoing which is currently the boolean value true but what does "target.value" retrieve? Can someone explain that part to me?

Also, just to make sure that I'm understanding this properly: is the variable name equal to event.target.name or am I understanding this incorrectly?

Thanks for your help.

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.name === 'isGoing' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}

I'm going through documentation on React.js on this website and came across code that I was confused by.

From what I understand, the prefilled state of the isGoing checkbox will be true (hence checked) whereas the numberOfGuests is 2.

The part I get confused on is the handleInputChange() function which sets the variable target equal to event.target - it's a pre-built attribute that returns the DOM element that triggered the event. The value variable, allows for target.name to retrieve the name and assigns it to target.checked as a truthy and target.value as a falsy. The "target.checked" retrieves the current state of isOnGoing which is currently the boolean value true but what does "target.value" retrieve? Can someone explain that part to me?

Also, just to make sure that I'm understanding this properly: is the variable name equal to event.target.name or am I understanding this incorrectly?

Thanks for your help.

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.name === 'isGoing' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}
Share Improve this question asked Jul 13, 2020 at 2:06 Not Me.Not Me. 1351 gold badge1 silver badge8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Question 1

The part I get confused on is the handleInputChange() function which sets the variable target equal to event.target - it's a pre-built attribute that returns the DOM element that triggered the event. The value variable, allows for target.name to retrieve the name and assigns it to target.checked as a truthy and target.value as a falsy. The "target.checked" retrieves the current state of isOnGoing which is currently the boolean value true but what does "target.value" retrieve?

Answer 1

React uses synthetic events that are quickly returned back to the event pool for reuse, so it is mon to save or destructure the event object to save into state, which is also asynchronous in nature, i.e. the state update doesn't occur immediately and the event object can be nullified and returned back to the event pool before the state update is processed.

handleInputChange(event) {
  // save the target object for future reference
  const target = event.target;

  // Check if the target is the checkbox or text input to save the value
  const value = target.name === 'isGoing' ? target.checked : target.value;

  // Save the input name, i.e. name = state object
  const name = target.name;

  this.setState({
    [name]: value
  });
}

How this works

The handler is accessing the name and check/value of the input, so by providing the same name to the inputs that are used in the state, the handler can dynamically save the correct value to the correct state property.

I.E. if the checkbox is toggled, then the target name is "isGoing" and the value is the target checked value, true or false. The setState resolves to something similar to

this.setState({ isGoing: true });

The more mon, or more generic, handler is to check the type instead to correctly access the checked property, or the normal value property.

handleInputChange(event) {
  // Destructure type, checked, name, and value from event.target
  const { type, checked, name, value } = event.target;
  this.setState({ [name]: type === 'checkbox' ? checked : value });
}

but what does "target.value" retrieve?

Generally, in this case it is simply accessing the target.value field of potentially any input that is using handleInputChange as a callback. In this specific case it will be the value of the "numberOfGuests" input.

Question 2

Also, just to make sure that I'm understanding this properly: is the variable name equal to event.target.name or am I understanding this incorrectly?

Answer 2

Yes, const name = target.name; is simply saving the event's target name to a variable called name. Similarly, const { name } = target is equivalent.

but what does "target.value" retrieve? Can someone explain that part to me?

The code is creating a dynamic changeHandler for a form that uses two types of inputs: number and checked. Text/number inputs have a value property, while checked inputs have a checked property. Therefor, a ternary statement is used to return either target.checked for when target.name matches the name of the only checkbox input ("isGoing"), or target.value for all other inputs (in this case just "numberOfGuests").

 is the variable name equal to event.target.name 

Continuing with the dynamic concept, variable name is indeed equated to target.name for readability purposes (it shortens target.name to name, just like target.name shortens e.target.name). Then, name gets passed as the property key to update within state. So if an input's name is "numberOfGuests", and there exists a state property called "numberOfGuests", then that state property will get updated. If no state property exists, react would just create a new property within state.

Overall, the goal is to create 1 onChange event handeler that can be used for all inputs, and for any state property, rather than giving each input its own unique handler.

发布评论

评论列表(0)

  1. 暂无评论