【问题标题】:Formik component changing an uncontrolled input of type text to be controlledFormik 组件更改要控制的类型文本的不受控输入
【发布时间】:2018-11-08 23:01:10
【问题描述】:

我将 Formik 与一个数组一起使用,其中项目从父级传递并像这样检索:

updateState (){
    this.state.choices = this.props.choices
    this.state.questionId = this.props.questionId
  }
  render() {
    this.updateState()
    var choices = this.state.choices
    console.log(choices)
    return ( ...

我最初将这些值初始化为空或 0:

  constructor(props){
    super(props);
    this.state = {
      choices : [],
      questionId: 0
    };
  }

虽然这看起来应该可行,但我收到一个错误,即组件正在更改要控制的文本类型的不受控制的输入。了解这是由于我使用了 this.state,但我不确定如何实际解决此问题。

到目前为止,由于我使用的是 Formik,我所做的是将我的导出更改为如下所示:

  export default withFormik({
  mapPropsToValues: (props) => ({
    choices: [{
    id: '',
    value: '',
    weight: '',
    impact: ''}]
  }),
})(Choices)

目前还不清楚我是否应该使用映射道具,或者我是否应该使用类似的东西:

export default withFormik({
  mapPropsToValues: (props) => ({

    id: '',
    value: '',
    weight: '',
    impact: ''
  }),
})(Choices)

我所知道的是,我无法单击以将新对象推送到我正在使用的数组上,因此该功能基本上被冻结,直到我能够弄清楚未/受控输入元素的状态。

知道我哪里出错了吗?

【问题讨论】:

  • 你不应该像this.state.choices那样改变状态。改用setState,在构造函数中设置它,或者如果可以的话直接使用道具。
  • 改变了,仍然得到不受控制的错误。好地方,谢谢

标签: javascript reactjs forms formik


【解决方案1】:

修复 HTML 和 {choices[index].id} 位清除了这个错误。

例如:

<div className="col">
                        <label htmlFor={choices[index].id}>{choices[index].id}</label>
                        <Field name={choices[index].id} placeholder={choices[index].value} type="text"/>
                        <ErrorMessage name={choices[index].id} component="div" className="field-error" />
                      </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 2020-10-07
    • 2020-01-29
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多