【问题标题】:Object destructuring in the function parameters in reactreact中函数参数中的对象解构
【发布时间】:2022-06-29 08:57:25
【问题描述】:

我是 ES6 功能的新手,我有以下代码,

我有以下组件。

    function ToDo() {
    
      const onChange = ({target: {value}}) => {
        console.log(target)
      }
     
    
    return (
    <input type="text" onChange={onChange} value={item.text} /> 
    )
}

这里我没有理解onChange函数中对象解构的部分。应该是event.target.value

谢谢

【问题讨论】:

  • 它的意思是“给我一个参数对象的属性target,然后给我target对象的属性value”。我不认为它特别可读。
  • onChange 期望事件对象作为参数。事件对象具有target 属性,而该属性又具有value 属性。所以,本质上,你可能会认为解构函数参数是一种表达(通过输入对象的形状)精确嵌套属性的方式,它成为函数体内具有相应名称的变量。

标签: reactjs


【解决方案1】:

这里const onChange = ({target: {value}})=&gt; ... on change 参数是您从事件中提取目标的event 对象,因为目标本身是一个对象,然后您从target 中提取value

event looks this shape: { ..., target: { ..., value: 'some value' } }

【讨论】:

    【解决方案2】:

    对象解构

    对象解构只是从对象中提取值的语法糖。请参阅以下内容:

    const person = {name: "Peter", computer: {model: "macbook", ram: 16}}
    const { name } = person; // this would give "Peter"
    const { computer } = person; // this would give {model: "macbook", ram: 16}
    
    // now the tricky part. Just re-uses the same destructuring-syntax twice :) 
    const { computer: { model }} = person; 
    console.log(model) // gives "macbook"
    
    // the lines above are essentially the same as this: 
    const { computer } = person; // first getting computer 
    const { model } = computer; // then getting the model
    console.log(model); //also gives "macbook"
    

    您的代码

    如果您记录value 而不是target,您应该会看到event.target.value 的值。

    function ToDo() {
      const onChange = ({ target: { value } }) => {
        console.log(target, value);
      };
    
      return <input type="text" onChange={onChange} value={item.text} />;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-17
      • 2020-07-30
      • 1970-01-01
      • 2012-04-17
      • 2017-11-14
      • 2019-04-18
      • 1970-01-01
      相关资源
      最近更新 更多