简体   繁体   English

React.js 的 event.target.value 问题

[英]event.target.value question with React.js

I'm going through documentation on React.js on this website and came across code that I was confused by.我正在浏览这个网站上关于 React.js 的文档,并遇到了让我感到困惑的代码。

From what I understand, the prefilled state of the isGoing checkbox will be true (hence checked) whereas the numberOfGuests is 2.据我了解,isGoing 复选框的预填充 state 将为真(因此选中),而 numberOfGuests 为 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.我感到困惑的部分是 handleInputChange() function ,它将变量target设置为等于 event.target - 这是一个预构建的属性,它返回触发事件的 DOM 元素。 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. value变量允许 target.name 检索名称并将其分配给 target.checked 作为真值和 target.value 作为假值。 The "target.checked" retrieves the current state of isOnGoing which is currently the boolean value true but what does "target.value" retrieve? “target.checked”检索 isOnGoing 的当前 state,当前 boolean 值为 true,但“target.value”检索什么? 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?另外,只是为了确保我正确理解这一点:变量名称是否等于event.target.name或者我是否理解错误?

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>
    );
  }
}

Question 1问题 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.我感到困惑的部分是 handleInputChange() function ,它将变量 target 设置为等于 event.target - 这是一个预构建的属性,它返回触发事件的 DOM 元素。 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. value 变量允许 target.name 检索名称并将其分配给 target.checked 作为真值和 target.value 作为假值。 The "target.checked" retrieves the current state of isOnGoing which is currently the boolean value true but what does "target.value" retrieve? “target.checked”检索 isOnGoing 的当前 state,当前 boolean 值为 true,但“target.value”检索什么?

Answer 1答案 1

React uses synthetic events that are quickly returned back to the event pool for reuse, so it is common to save or destructure the event object to save into state, which is also asynchronous in nature, ie 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. React 使用合成事件快速返回到事件池以供重用,因此通常保存或解构事件 object 以保存到 state 中,这在本质上也是异步的,即 Z9ED39E2EA931586B73 更新不会立即发生。在处理 state 更新之前,事件 object 可以无效并返回到事件池。

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.处理程序正在访问输入的名称和检查/值,因此通过为 state 中使用的输入提供相同的名称,处理程序可以将正确的值动态保存到正确的 state 属性中。

IE if the checkbox is toggled, then the target name is "isGoing" and the value is the target checked value, true or false . IE 如果复选框被切换,则目标名称为"isGoing" ,值为目标选中值, truefalse The setState resolves to something similar to setState解析为类似于

this.setState({ isGoing: true });

The more common, 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?但是“target.value”检索什么?

Generally, in this case it is simply accessing the target.value field of potentially any input that is using handleInputChange as a callback.通常,在这种情况下,它只是访问可能使用handleInputChange作为回调的任何输入的target.value字段。 In this specific case it will be the value of the "numberOfGuests" input.在这种特定情况下,它将是"numberOfGuests"输入的值。

Question 2问题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?另外,只是为了确保我正确理解这一点:变量名称是否等于 event.target.name 或者我是否理解错误?

Answer 2答案 2

Yes, const name = target.name;是的, const name = target.name; is simply saving the event's target name to a variable called name .只是将事件的目标名称保存到名为name的变量中。 Similarly, const { name } = target is equivalent.同样, const { name } = target是等价的。

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.该代码正在为使用两种类型输入的表单创建动态 changeHandler:数字和检查。 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").因此,当 target.name 与唯一的复选框输入(“isGoing”)的名称匹配时,使用三元语句返回 target.checked,或者为所有其他输入(在本例中为“numberOfGuests”)返回 target.value。

 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).继续动态概念,出于可读性目的,变量名称确实等同于 target.name(它将 target.name 缩短为 name,就像 target.name 缩短 e.target.name 一样)。 Then, name gets passed as the property key to update within state.然后,名称作为属性键传递,以在 state 中更新。 So if an input's name is "numberOfGuests", and there exists a state property called "numberOfGuests", then that state property will get updated.因此,如果输入的名称是“numberOfGuests”,并且存在一个名为“numberOfGuests”的 state 属性,则该 state 属性将得到更新。 If no state property exists, react would just create a new property within state.如果不存在 state 属性,react 只会在 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.总体而言,目标是创建 1 个可用于所有输入和任何 state 属性的 onChange 事件处理程序,而不是为每个输入提供自己唯一的处理程序。

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

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