[英]How to override className on extended component?
I am trying to position this component differently on a certain page. 我试图在某个页面上以不同的方式放置此组件。 But when I provide it with another className property it is only using the original class's styling that was provided when declaring the component.
但是,当我为它提供另一个className属性时,它仅使用声明组件时提供的原始类的样式。
Component: 零件:
import React, { Component } from 'react';
import styles from './label.css';
class Label extends Component {
render() {
return (
<div className={styles.labelClass} />
);
}
}
export default Label;
Page where I want to position it differently: 我要以其他方式放置它的页面:
import React, { Component } from 'react';
import styles from './page.css';
import Label from '../common/label.jsx';
class Page extends Component {
render() {
return (
<div>
<Label className={styles.positionLeft} />
</div>
);
}
}
export default Page;
Normally I would do this with custom styling but I have to use media queries so this isn't possible in this situation. 通常,我会使用自定义样式来执行此操作,但是我必须使用媒体查询,因此在这种情况下是不可能的。
Since <Label>
is a custom component, you can to manually pass the className
prop down. 由于
<Label>
是自定义组件,因此您可以手动向下传递className
属性。
This is a good use case for default props ! 这是默认道具的好用例!
class Label extends Component {
render() {
return (
<div className={this.props.className} />
);
}
}
Label.defaultProps = {
className: styles.labelClass
}
That way, if no className
is provided to Label
, it will use the labelClass
style, otherwise, it will use the prop. 这样,如果没有为
Label
提供className
,它将使用labelClass
样式,否则将使用prop。
You need to explicitly reference the className
property from Label
's props - try: 您需要从
Label
的props中显式引用className
属性-尝试:
import React, { Component } from 'react';
import styles from './label.css';
class Label extends Component {
render() {
let { className } = this.props
if (!className) {
className = styles.labelClass
}
return (
<div className={className} />
);
}
}
export default Label;
I fixed it by adding another optional property customClass to the component. 我通过向组件添加另一个可选属性customClass来修复了它。
Label 标签
import React, { Component } from 'react';
import styles from './label.css';
class Label extends Component {
render() {
return (
<div className={styles.labelClass + ' ' + this.props.customClass} />
);
}
}
export default Label;
Page 页
import React, { Component } from 'react';
import styles from './page.css';
import Label from '../common/label.jsx';
class Page extends Component {
render() {
return (
<div>
<Label customClass={styles.positionLeft} />
</div>
);
}
}
export default Page;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.