字段值不在自定义组件中打印

时间:2017-02-21 01:48:43

标签: reactjs redux-form

由于某种原因,Field值没有打印到我的customComponent const。

const CustomComponent = function(field) {
  console.log(field.input.value); //blank, no value
  return (
    <div>
      <input { ...field.input } type={field.type} placeholder={field.placeholder} className={field.className} />
    </div>
  );
}

......

<Field name="test" component={CustomComponent} type="text" placeholder="Test" value="testvalue" />

1 个答案:

答案 0 :(得分:1)

这里的问题是您尝试直接设置value redux-form组件的Field,但redux-form的全部概念是,您允许图书馆负责处理。

如果您想为redux-form Field设置初始值,请使用initialValues -prop来执行此操作(请参阅文档中的"Initialize from state"示例)

将redux connect -decorator粘贴在reduxForm -decorator上方,您可以使用redux状态设置初始形式值

class MyForm extends Component {
  render() {
    return (
      <form>
        { /* This one will have the static initial value */ }
        <Field
          name="staticValue"
          component={ CustomComponent }
          type="input"
          placeholder="Static Placeholder"
        />
        { /* This one will have the dynamic initial value */ }
        <Field
          name="dynamicValue"
          component={ CustomComponent }
          type="input"
          placeholder="Dynamic Placeholder"
        />
      </form>
    )
  }
}

const mapStateToProps = reducers => {
  return {
    initialValues: {
      staticValue: 'some static default initial value',
      dynamicValue: reducers.dynamicReducer.dynamicValue
    }
  }
}

@connect(mapStateToProps)
@reduxForm({ formName: 'MyForm' })
class MyFormContainer extends Myform {}

希望这有帮助!