【问题标题】:name prop going as undefined名称道具未定义
【发布时间】:2018-07-10 07:55:20
【问题描述】:

我正在使用 redux-form 并将 material-ui 的 TextField 作为 prop 发送到 redux-form 的字段。但其他属性都按预期进行。

<Field
    id="firstName"
    name="firstName"
    floatingLabelText="Username"
    errorText={this.state.firstNameError}
    component={TextInputField}
/>

下面是 TextInputField 组件的代码

import React from 'react';
import PropTypes from 'prop-types';
import TextField from 'material-ui/TextField';
import _noop from 'lodash/noop';

const TextInputField = ({
    hintText,
    id,
    name,
    className,
    defaultValue,
    floatingLabelText,
    errorText,
    onFocus,
    onChange,
    onBlur
}) => {

return (
    <TextField
        hintText={hintText}
        id={id}
        name={name}
        className={className}
        defaultValue={defaultValue}
        floatingLabelText={floatingLabelText}
        errorText={errorText}
        onFocus={onFocus}
        onChange={onChange}
        onBlur={onBlur}
    />
);
};

export default TextInputField;

这里的问题是名称 prop 在我使用组件的地方未定义。我不知道这是在哪里发生的。当我安慰名称道具时,它是未定义的。

【问题讨论】:

  • 使用 rest 运算符而不是在那里写所有参数。使用三元运算符进行空检查,并确保将名称传递到此无状态组件中

标签: reactjs material-ui redux-form


【解决方案1】:

根据文档,您的 TextInputField 应该接受 inputmeta 道具。 input 属性具有 name 属性。

来自redux-form docs

redux-form提供的props分为input和meta 对象。

任何传递给 Field 的自定义 props 都将被合并到 props 对象中 与输入和元对象处于同一级别。

这是quote from input props section

input.name : String 当嵌套在 FormSection 中时,返回 name 属性 以 FormSection 名称为前缀。否则,返回名称道具 你传入的那个。

所以你的组件应该是这样的:

const TextInputField = ({
    input: { 
      name,
      onChange,
      onBlur,
      onFocus
    },
    hintText,
    id,
    className,
    defaultValue,
    floatingLabelText,
    errorText
}) => (
  <TextField
      hintText={hintText}
      id={id}
      name={name}
      className={className}
      defaultValue={defaultValue}
      floatingLabelText={floatingLabelText}
      errorText={errorText}
      onFocus={onFocus}
      onChange={onChange}
      onBlur={onBlur}
    />
);

甚至更简单:

const TextInputField = ({ input, meta, ...rest }) => (
  <TextField {...input} {...rest} />
);

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2018-04-10
    相关资源
    最近更新 更多