【问题标题】:escape square brackets with formik用 formik 转义方括号
【发布时间】:2019-03-08 10:53:05
【问题描述】:

我在 react 中使用 Formik,但在使用验证以在屏幕上显示错误时遇到方括号问题。我尝试使用"\[",但没有成功。使用诸如“text”或“text-i”甚至“text(i)”之类的东西可以正常工作,但我只遇到方括号的问题。

isDataValid = (values: KeyValue<any>) => {
        let errors: FormikErrors<KeyValue<any>> = {};

      (for let i=0; i<... etc) {
        if (!values["text[i]"]) {
            errors["text[i]"] = "Insert title";
        }
     }  

        return errors;

有什么建议吗?

【问题讨论】:

  • 你能提供更多的上下文吗?

标签: reactjs formik


【解决方案1】:

不使用i 似乎是问题所在。为了在这种情况下在for 循环中使用i,您可以使用模板文字或+

使用模板文字:

(for let i=0; i<... etc) {
    if (!values[`text[${i}]`]) {
        errors[`text[${i}]`] = "Insert title";
    }
 } 

使用+

(for let i=0; i<... etc) {
    if (!values["text[" + i + "]"]) {
        errors["text[" + i + "]"] = "Insert title";
    }
 } 

请注意使用模板字面量可能会导致兼容性问题,参考:https://caniuse.com/#feat=template-literals

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-10
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2012-02-16
    • 2012-10-28
    相关资源
    最近更新 更多