【发布时间】:2020-01-20 13:05:28
【问题描述】:
创建一个类似于以下内容的函数是否安全有效:
style = {
border: '1px solid primary'
}
并将其转换为:
style = {
border: '1px solid rgb(0, 0, 0)'
}
在将其作为道具提供给如下样式组件之前?
const StyledContainer = styled.div`
border: ${props => props.border};
`;
我担心它会随着时间的推移而变慢,因为我需要每次迭代每个样式对象并在每个项目上使用类似 string.replace() 的东西。我也担心 CSS 注入并且不熟悉它们。我这样说是因为我的项目中有很多文本输入字段。
为了澄清,我确实有它的工作:
const replaceStringWithTheme = (string, theme) => {
const modifiedString = string
.replace("primary", theme.primary)
.replace("secondary", theme.secondary)
.replace("background", theme.background)
.replace("xs", "0.5rem")
.replace("sm", "1rem")
.replace("md", "1.5rem")
.replace("lg", "2.0rem")
.replace("xl", "2.5rem");
return modifiedString;
};
const replacePropsWithTheme = (props, theme) => {
const cloneObject = { ...props };
for (let [key, prop] of Object.entries(cloneObject)) {
if (typeof prop === "string") {
cloneObject[key] = replaceStringWithTheme(prop, theme);
}
}
return cloneObject;
};
export function Container(props) {
const theme = useThemeState();
const modProps = replacePropsWithTheme(props, theme);
return <StyledContainer {...modProps}>{props.children}</StyledContainer>;
}
const StyledContainer = styled.div`
width: ${props => props.width};
height: ${props => props.height};
margin: ${props => props.margin};
padding: ${props => props.padding};
background: ${props => props.background};
border: ${props => props.border};
`;
我只是想知道,这真的是个坏主意吗?我正在克隆通过的道具。由于某种原因,似乎可以通过更改默认的 props 对象来间接执行一些任意代码。
【问题讨论】:
-
你让用户输入样式吗?
-
我只让他们选择主题颜色,例如色轮上的主要或次要颜色。我担心我克隆了传递给组件的道具对象并迭代每个属性。我不认为代码会以不同的方式执行,但我不确定。
标签: javascript css reactjs styled-components