【发布时间】:2021-06-09 01:52:43
【问题描述】:
docs for styled-components show 其默认的 styled 导出接受单个参数:
styled- 这是默认导出。这是我们用来创建
styled.tagname辅助方法的低级工厂。- 参数
component/tagname- 说明
- 有效的反应组件 或者像
'div'这样的标记名。
我在这里强调了“有效的反应组件”,因为他们明确没有说这必须是由 styled 创建的 React 组件,尽管传统上是这样是这是如何使用的(以及documented under their Extending Styled section)。这方面的一个例子如下所示:
const RedBox = styled.div`
border: 1px solid black;
color: red;
`;
// Traditionally, the argument you pass to `styled` is
// a react element *created by a previous `styled` call*
const BlueBox = styled(RedBox)`
color: blue;
`;
function Example() {
return (
<div>
<RedBox>I am a red box</RedBox>
<BlueBox>I am a blue box</BlueBox>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://unpkg.com/react@17.0.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-is@17.0.1/umd/react-is.production.min.js"></script>
<script src="https://unpkg.com/styled-components@5.2.1/dist/styled-components.js"></script>
<div id="root"></div>
以上内容不足为奇。
但是,我的问题是 如果您将 非 样式的组件作为参数传递给 styled 调用会怎样?返回的元素不应该也获得样式吗?申请了吗?
考虑以下简单示例:
// Create two simple components, one functional, one class-based
const BoxFunctional = (props) => <div>{props.children}</div>;
class BoxClass extends React.Component {
render() {
return <div>{this.props.children}</div>
}
}
// Here, I pass a functional React Component to `styled`
const RedBoxFunctional = styled(BoxFunctional)`
color: red;
border: 1px solid black;
`;
// Again, passing another regular React component, this time a class component
const RedBoxClass = styled(BoxClass)`
color: red;
border: 1px solid black;
`;
function Example() {
return (
<div>
<p>The below two Boxes are regular react elements:</p>
<BoxFunctional>I am a functional box</BoxFunctional>
<BoxClass>I am a class box</BoxClass>
<hr />
<p>The below two boxes <em>should</em> be styled:</p>
<RedBoxFunctional>I am a functional red box</RedBoxFunctional>
<RedBoxClass>I am a class red box</RedBoxClass>
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://unpkg.com/react@17.0.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-is@17.0.1/umd/react-is.production.min.js"></script>
<script src="https://unpkg.com/styled-components@5.2.1/dist/styled-components.js"></script>
<div id="root"></div>
运行上面的 sn-p,你可以看到 styled 组件的样式不是,尽管它们扩展了一个“有效”的反应组件。
我有什么遗漏吗?文档不正确吗? styled 能否仅将样式应用于由先前的 styled 调用创建的现有 React 组件?
【问题讨论】:
标签: javascript reactjs styled-components