styled-components 中的 '.attrs()' 和 'props' 有什么区别?
what is difference between '.attrs()' and 'props' in styled-components?
const Input = styled.input.attrs(props => ({
// we can define static props
type: "text",
// or we can define dynamic ones
size: props.size || "1em",
}))`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
/* here we use the dynamically computed prop */
margin: ${props => props.size};
padding: ${props => props.size};
`;
render(
<div>
<Input placeholder="A small text input" />
<br />
<Input placeholder="A bigger text input" size="2em" />
</div>
);
本例取自官方文档
但是,我认为这段代码与以下代码相同:
const Input = styled.input`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
margin: ${props => props.size};
padding: ${props => props.size};
`;
render(
<div>
<Input placeholder="A small text input" />
<br />
<Input placeholder="A bigger text input" size="2em" />
</div>
);
我不明白 styled-components 中 '.attrs()' 和 'props' 之间的区别
如果有变化或其他东西,如动画等,请使用内联样式(通过 attrs
)
如果样式不经常更改,则使用具有静态和动态样式的样式化组件
已经发现了这个.
const Input = styled.input.attrs(props => ({
// we can define static props
type: "text",
// or we can define dynamic ones
size: props.size || "1em",
}))`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
/* here we use the dynamically computed prop */
margin: ${props => props.size};
padding: ${props => props.size};
`;
render(
<div>
<Input placeholder="A small text input" />
<br />
<Input placeholder="A bigger text input" size="2em" />
</div>
);
本例取自官方文档
但是,我认为这段代码与以下代码相同:
const Input = styled.input`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
margin: ${props => props.size};
padding: ${props => props.size};
`;
render(
<div>
<Input placeholder="A small text input" />
<br />
<Input placeholder="A bigger text input" size="2em" />
</div>
);
我不明白 styled-components 中 '.attrs()' 和 'props' 之间的区别
如果有变化或其他东西,如动画等,请使用内联样式(通过 attrs
)
如果样式不经常更改,则使用具有静态和动态样式的样式化组件
已经发现了这个