Skip to content
← Back to rules

react/style-prop-object 可疑

它的作用

要求 style 属性的值必须是对象,或是一个对象类型的变量。

为什么这是个问题?

在使用 JSX 时,style 属性期望接收一个将样式属性映射到对应值的对象。

示例

以下为 错误 的代码示例:

jsx
<div style="color: 'red'" />
<div style={true} />
<Hello style={true} />
const styles = true;
<div style={styles} />

React.createElement("div", { style: "color: 'red'" });
React.createElement("div", { style: true });
React.createElement("Hello", { style: true });
const styles = true;
React.createElement("div", { style: styles });

以下为 正确 的代码示例:

jsx
<div style={{ color: "red" }} />
<Hello style={{ color: "red" }} />
const styles = { color: "red" };
<div style={styles} />

React.createElement("div", { style: { color: 'red' }});
React.createElement("Hello", { style: { color: 'red' }});
const styles = { height: '100px' };
React.createElement("div", { style: styles });

配置

此规则接受一个配置对象,包含以下属性:

allow

type: string[]

default: []

允许任意类型 style 属性值的组件名称列表。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "plugins": ["react"],
  "rules": {
    "react/style-prop-object": "error"
  }
}
bash
oxlint --deny react/style-prop-object --react-plugin

参考资料