【问题标题】:reactjs: Es6 unable to understand the syntaxreactjs: Es6 无法理解语法
【发布时间】:2021-10-14 12:00:42
【问题描述】:

我正在使用react hook表单,遇到了这个使用Controller for material ui TextField的例子

({ field: { ref, ...field } }) => (
                  <TextField
                    {...field}
                    inputRef={ref}
                    fullWidth
                    required
                    label="Current Password"
                    type="password"
                    margin="dense"
                  />
                )

下面是什么意思

({ field: { ref, ...field } })

还有{...field}(扩展为什么)

                  <TextField
                    {...field}
                    inputRef={ref}
                    fullWidth
                    required
                    label="Current Password"
                    type="password"
                    margin="dense"
                  />

总码是

              <Controller
                name="old_password"
                control={control}
                render={({ field: { ref, ...field } }) => (
                  <TextField
                    {...field}
                    inputRef={ref}
                    fullWidth
                    required
                    label="Current Password"
                    type="password"
                    margin="dense"
                  />
                )}
              />

【问题讨论】:

  • 它将一个对象解构为一个名为ref的变量,并将obj.field.ref作为一个值赋值,并将obj.field对象中的所有其余部分减去ref键和将其分配给变量field{...field} JSX 语法只是意味着它通过 props 将对象传播到组件上
  • obj.field minus the ref key : 没拿到这部分
  • 好吧,对象中的所有内容都减去了ref 键...所以如果你有这样的对象:{ ref: 1, two: 2, three: 3 } 并且做了const { ref, ...field } = obj,那么你的ref 就是1 和@ 987654340@ 是{ two: 2, three: 3 }
  • 所以在const { ref, ...field } = obj - field 只是一个表示或变量名。我更喜欢看到 obj,即 const { ref, ...obj } = obj

标签: reactjs ecmascript-6 react-hook-form


【解决方案1】:

它只是一个普通的组件......这样想:

const Component = (props) =>{
    const {ref, ...field} = props.field
    return(
          <TextField
            {...field}
            inputRef={ref}
            fullWidth
            required
            label="Current Password"
            type="password"
            margin="dense"
          />
    )
} 

...field 只是扩展的原始字段props.field 减去ref 属性。在这种情况下,必要的原因 TextField 期望 ref 由 inputRef 持有

【讨论】:

  • props.field minus ref property : 你能解释一下分手吗
猜你喜欢
  • 2017-08-23
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 2023-03-03
  • 2023-03-06
相关资源
最近更新 更多