gpt4 book ai didi

javascript - 如何在我的 React 应用程序中使用样式化组件?

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:10 25 4
gpt4 key购买 nike

我很难命名这个问题,它看起来很宽泛,所以,请原谅我哦版主。我正在尝试 styled components第一次尝试将其集成到我的 React 应用程序中。到目前为止,我有以下内容:

import React from 'react';
import styled from 'styled-components';

const Heading = styled.h1`
background: red;
`;

class Heading extends React.Component {

render () {

return (
<Heading>
{this.props.title}
</Heading>
);
}

}

export default Heading;

所以,只是一个普通的类,但随后我在顶部导入 styled components,定义 const Heading,我在其中指定了一个 Heading 实际上只是一个样式化的 h1。但是我收到一条错误消息,指出 Heading 是重复声明,因为我还说 class Heading...

我显然在这里完全遗漏了一些东西。所有在线示例实际上并没有显示您如何将其与 React 一起使用。 IE。我在哪里定义我的类、我的构造函数、设置我的状态等。

我是否必须将带样式的组件移动到它自己的文件中,即:

import styled from 'styled-components';

const Heading = styled.h1`
background: red;
`;

export default Heading;

然后创建一个 React 组件,用作各种包装器,例如'标题包装器':

import React from 'react';
import Heading from './Heading';

class HeadingWrapper extends React.Component {

render () {

return (
<Heading>
{this.props.title}
</Heading>
);
}

}

export default HeadingWrapper;

非常感谢对此有一点澄清!谢谢 :)

最佳答案

styled.h1`...` (例如)返回一个像 <h1> 一样工作的 React 组件.换句话说,您使用 <h1>像这样:

<h1>h1's children</h1>

...所以当你做 const Heading = styled.h1`...`; ,您将使用 <Heading>同样的方法:

<Heading>Heading's children</Heading>

如果你想要一个行为不同的组件,例如一个使用 title Prop 而不是 children ,您将需要定义这样一个组件,并且它的名称需要与您已经定义的 Heading 组件不同。

例如:

const styled = window.styled.default;

const Heading = styled.h1`
background: red;
`;

const TitleHeading = ({title}) => <Heading>{title}</Heading>;

// ...or...

class StatefulTitleHeading extends React.Component {
render() {
return <Heading>{this.props.title}</Heading>;
}
}

ReactDOM.render(
<div>
<Heading>I'm Heading</Heading>
<TitleHeading title="I'm TitleHeading"/>
<StatefulTitleHeading title="I'm StatefulTitleHeading"/>
</div>,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/styled-components@1.4.3/dist/styled-components.js"></script>
<div id="container"></div>

不过,坦率地说,使用 styled.h1 返回的组件更有意义直接:

const Heading = styled.h1`...`;
export default Heading;

// ...then...

<Heading>Children go here</Heading>

children的语义已经很清楚了,使用<Heading title="Children go here"/>反而大大减损了这一点。

关于javascript - 如何在我的 React 应用程序中使用样式化组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42374080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com