[英]trying to conditionally style a react component but the style isn't applying
it's a simple code that changes the input area outline colour if it fails my validation but it is taking no style from my js and I don't know what's wrong.这是一个简单的代码,如果我的验证失败,它会更改输入区域的轮廓颜色,但它没有从我的 js 中获取样式,我不知道出了什么问题。 the element style shows up when I inspect the element but it just doesn't render
当我检查元素时会显示元素样式,但它只是不呈现
export const Form = ({ urlText }) => {
let inputStyle = {
border: "red 10px !important",
};
const [text, setText] = useState("");
function ValidateUrl(link) {
var urlFormat =
/[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
if (link.match(urlFormat)) {
return true;
} else {
return false;
}
}
const onSubmit = (e) => {
e.preventDefault();
if (ValidateUrl(text)) {
urlText(text);
} else {
inputStyle = {
outline: "solid 1px hsl(0, 87%, 67%)",
};
alert("wrong url");
}
};
return (
<div>
<div>
<form onSubmit={onSubmit} className="form">
<div>
<input
onChange={(e) => setText(e.target.value)}
style={inputStyle}
type="text"
size="30"
id="url"
placeholder="Shorten a link here..."
/>
</div>
<div>
<button type="submit" className="main-btn">
Shorten It!
</button>
</div>
</form>
</div>
</div>
);
};
the border syntax should look like this: width |边框语法应如下所示: width | style |
风格| color so: border: 10px solid red;
颜色如此:边框:10px纯红色; and also delete !important it is unnecessary
并删除 !important 它是不必要的
Can you directly try可以直接试试吗
style={{border: '10px solid red'}}
if you wanna hold these types of styles you can use styled component.如果你想保存这些类型的样式,你可以使用样式组件。
decleare a use state [pressed,setPressed] = useState(false);清除使用状态 [pressed,setPressed] = useState(false); then use this setPressed(true) in on press instead of inputStyle
然后在按下时使用这个 setPressed(true) 而不是 inputStyle
if (ValidateUrl(text)) {
urlText(text);
} else {
setPressed(true);
alert("wrong url");
}
and finally in the input use this最后在输入中使用这个
style={pressed? {outline: " 1px solid hsl(0, 87%, 67%)"} : {border: '10px solid red'}}
I am not sure about hsl(0, 87%, 67%) part but if it is true this should work.我不确定 hsl(0, 87%, 67%) 部分,但如果这是真的,这应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.