我在React项目中有一个CTA组件。我在我的页面上使用了几次。我想更改其中一个CTA用途的文本的背景颜色和颜色。我怎样才能做到这一点?
我尝试将一个className添加到其中一个CTA组件并设置样式但没有改变。我还尝试添加内联样式。我的App.js文件有CTA组件:
<CTA word='CTA HERE' className='unique-cta-styling' style={{color: 'black'}}/>
我的CTA组件是这样的:
import '../../style/CTA.scss'
const CTA = ({ ...props }) => {
return (
<div
class='CTA'
onClick={props.onClick}
>
{props.word}
</div>
)
}
export default CTA
className='unique-cta-styling'
仅适用于HTML标签的先验。 React组件可能会或可能不会与className
道具做任何事情。
要设置React组件的样式,可以将其包装在您控制的<div>
中。
<div className='cta-styling' style={{background-color: 'black'}}>
<CTA word='CTA HERE' />
</div>
在这里,您还可以设置由CTA组件呈现的html元素的样式。例如,要设置CTA组件呈现的<span>
元素的样式,可以将以下内容添加到CSS文件中:
.cta-styling span {
color: 'red';
}
编辑:因为您可以编辑组件,所以您可以将道具传递给孩子。
const CTA = ({word, ...props}) => {
return (
<div {...props}>
{word}
</div>
)
}
我建议使用Styled Components
。哪个可以读到关于here。他们还有一个很好的按钮示例,您可以阅读。
import React from 'react';
import StyledCTA from '../../style/styled-CTA';
const CTA = ({
onClick,
word,
backgroundColor,
textColor,
}) => (
<StyledCTA
onClick={onClick}
backgroundColor={backgroundColor}
textColor={textColor}
>
{word}
</StyledCTA>
);
export default CTA;
然后在您的样式化组件文件中,您可以拥有以下内容:
import styled from 'styled-components';
const getBackgroundColor = ({ backgroundColor }) => backgroundColor || 'red';
const getTextColor = ({ textColor }) => textColor || 'black';
export default styled.button`
// Other static styling goes here
background-color: ${getBackgroundColor};
color: ${getTextColor};
`;
这应该适合你。你可以看到它在这个链接上运行[https://jsfiddle.net/wu7kv15q/1/]。
代码中的主要问题是,在自定义组件的情况下,您必须将ClassName显式映射到html元素。
class Test extends React.Component {
render() {
return (
<CTA word='CTA HERE' className='unique-cta-styling' style={{color: 'red'}}/>
)
}
}
const CTA = ({ word,className,style,onClick }) => {
return (
<div
className={`CTA ${className}`}
onClick={onClick}
style={style}
>
{word}
</div>
)
}
ReactDOM.render(
<Test />,
document.getElementById('container')
);
我建议你使用styled-components
使用样式化组件,您可以执行以下操作。你可以在js文件(styles.js)中设置这个组件的样式:
export const YourComponent= styled.button`
margin-top: 10px;
margin-bottom: 5px;
background-color: ${props => {
switch (props.yourProps) {
case "Status01":
return "#0D47A1";
case "Status02":
return "#2E7D32";
default:
return "#FF8F00";
}
}};
&:hover {
background-color: ${props => {
switch (props.yourProps) {
case "Status01":
return "#0D47A1";
case "Status02":
return "#2E7D32";
default:
return "#FF8F00";
}
}};
}
`;
并将其导入您的组件文件中。
import { YourComponent } from './styles'
<YourComponent
yourProps="Status01"
>
Component Name
</YourComponent>
我希望它对你有所帮助!