我可以向 React 中的元素添加可选属性吗?
Can I add optional attributes to an element in React?
目前,在我的 React 应用程序中我有这个,
<input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />
如果我有更多的造型要做,一遍又一遍地检查相同的条件就没有意义了,对吗?我希望将整个 style 属性设为可选;像这样,
<input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
但我知道这不是正确的语法。没有更好的方法吗?
您需要将逻辑放入样式属性中,并在有效的情况下为其传递一个中性元素(或将其提取到一个变量中)。
我认为这应该可以解决问题:
<input style={valid ? {} : { borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
一个选项是创建一个变量:
const inputStyle = !valid ? {
borderColor: "red",
boxShadow: "rgb(2, 0, 0)"
} : {};
<input style={inputStyle}/>
它与您当前拥有的相同,但您可以根据需要向变量添加新属性,而无需增加 input
标记中的比较量。
您可以在 render 方法中将样式定义为对象,然后使用 ternary and spread 运算符将其作为 prop 选择性地分配给组件。
const styles = {
borderColor: "red",
boxShadow: "rgb(2, 0, 0)",
// etc...
};
return (
<input { ...(valid ? { styles } : {}) } />
);
您应该使用 className 添加样式 类 conditionally.You 可以使用 classnames 包作为对
的回答
目前,在我的 React 应用程序中我有这个,
<input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />
如果我有更多的造型要做,一遍又一遍地检查相同的条件就没有意义了,对吗?我希望将整个 style 属性设为可选;像这样,
<input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
但我知道这不是正确的语法。没有更好的方法吗?
您需要将逻辑放入样式属性中,并在有效的情况下为其传递一个中性元素(或将其提取到一个变量中)。 我认为这应该可以解决问题:
<input style={valid ? {} : { borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
一个选项是创建一个变量:
const inputStyle = !valid ? {
borderColor: "red",
boxShadow: "rgb(2, 0, 0)"
} : {};
<input style={inputStyle}/>
它与您当前拥有的相同,但您可以根据需要向变量添加新属性,而无需增加 input
标记中的比较量。
您可以在 render 方法中将样式定义为对象,然后使用 ternary and spread 运算符将其作为 prop 选择性地分配给组件。
const styles = {
borderColor: "red",
boxShadow: "rgb(2, 0, 0)",
// etc...
};
return (
<input { ...(valid ? { styles } : {}) } />
);
您应该使用 className 添加样式 类 conditionally.You 可以使用 classnames 包作为对