代码之家  ›  专栏  ›  技术社区  ›  JackTheKnife

ReactJS:更改特定元素ID的输入字段边框颜色

  •  0
  • JackTheKnife  · 技术社区  · 6 年前

    我很难根据选定元素的ID更改输入字段边框颜色。

    我试过香草JavaScript之类的

           fetch("/login?"+query, {
                method: "GET",
                headers: {
                    "Access-Control-Allow-Origin": "*"
                },
                credentials: "include"
            }).then(response => {
                status = response.status;
                return response.json()
            }).then(data => {
                if (status==200) {
                    //log in
                }
                else {
                    if (status==404) {
                      document.getElementById('user').style.border('1px solid red');
                      document.getElementById('password').style.border('1px solid red');
                    }
                }
            }).catch(err => {
                setErrors({
                    systemErr: err
                });
            })
    

    但失败的是一个错误,无法呈现修改过的子元素。

    此外,我还为必填字段设置了样式

    style={getStyles(touched, props.errors, 'password')}

    然后

    function getStyles (touched, error, fieldName) {
        if (errors[fieldName] && touched[fieldName]) {
            return {
                border: '1px solid red'
            }
        }
    };
    

    这很好,但当API不会返回任何内容时,我需要有一个边界。旁注:我正在使用带有Yup的Formik来验证必填字段。

    有什么建议吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ranjith    6 年前

    只需向组件添加状态,然后将其传递给组件样式即可。

        2
  •  1
  •   Prabhat Kumar    6 年前

    用这个代码替换你的行。

     document.getElementById('user').style.border = '1px solid red';
     document.getElementById('password').style.border ='1px solid red';
    

    您将边界作为函数调用,但它是一个属性。