使用React的styled-components样式化组件。 组件处理类组件。 我想将组件(componentA)与不同的组件(componentB)一起使用,并为其添加样式,但是我不知道该如何实现,所以请告诉我。
index.js
import React from "react";
import ReactDOM from "react-dom";
import ComponentA from "./componentA";
import ComponentB from "./componentB";
ReactDOM.render(
<div>
<ComponentA/>
<ComponentB/>
</div>,
document.getElementById("app")
);
componentA
import React, { Component } from "react"
import styled from "styled-components"
const Icon = styled.img`
width: 180px;
height: 60px;
`;
class ComponentA extends Component {
render() {
return (
<div>
<Icon src="hoge.png" />
</div>
);
}
}
export default styled(ComponentA)``;
componentB
import React from "react";
import styled from "styled-components";
import ComponentA from "./ComponentA";
const RestyleComponentA = styled(ComponentA)`
width: 360px;
height: 120px;
`;
export default class ComponentB extends Component {
render() {
<div>
<RestyleComponentA />
</div>
}
}
运行上面的代码将类似于下面的屏幕截图。
result of execute the above code
但是,我希望这样。
为什么我尝试覆盖的样式不会影响这两个组件?
我已经尝试过
谢谢
答案 0 :(得分:2)
您可以重新设置Icon的样式,而不是ComponentA的样式。导出图标组件以重复使用
import React from "react";
import styled from "styled-components";
import Icon from "./Icon";
const RestyleIcon = styled(Icon)`
width: 360px;
height: 120px;
`;
export default class ComponentB extends Component {
render() {
<div>
<RestyleIcon src="hoge.png" />
</div>
}
}
答案 1 :(得分:0)
根据Puneet Mahendra的回答,我对每个文件进行了如下编辑,并实现了样式覆盖。
如果您发现我编写的代码有误,请在评论中让我知道。
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import ComponentA from "./componentA";
import ComponentB from "./componentB";
ReactDOM.render(
<div>
<ComponentA/>
<ComponentB/>
</div>
, document.getElementById('root')
);
box.js
import React from "react";
class Box extends React.Component {
render() {
return (
<div className="box1">
<div className="box2">
{this.props.children}
</div>
</div>
);
}
}
export default Box;
icon.js
import styled from "styled-components";
const Icon = styled.img`
width: 100px;
height: 100px;
`;
export default Icon;
componentA
import React from "react";
import Box from "./box";
import Icon from "./icon";
class ComponentA extends React.Component {
render() {
return (
<Box>
<Icon src="hoge.png"/>
</Box>
);
}
}
export default ComponentA;
componentB
import React from "react";
import styled from "styled-components";
import Icon from "./icon";
import Box from "./box";
const RestyledIcon = styled(Icon)`
width: 200px;
height: 200px;
`;
class ComponentB extends React.Component {
render() {
return (
<Box>
<RestyledIcon src="hoge.png"/>
</Box>
);
}
}
export default ComponentB;
非常感谢您。