将默认道具样式与内联样式组合在一起



我有一个这样的组件

class SomeComponent extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<div
style={{...styles.container, ...this.props.containerStyles}} />
<div 
style={{...styles.headline, ...this.props.headlineStyles}} />
)
};
};
const styles = {
container: {
width: '50px'
height: '60px',
},
headline: {
color: 'red',
};
SomeComponent.defaultProps = {
backgroundColor = 'grey',
overflow: 'hidden',
fontSize: 20,
};

我想知道如何将styles.containerthis.props.containerStylesdefaultProps结合起来?想象一下,this.props.containerStyles只有backgroundColor,而不是overflow。我想要defaultPropsoverflow: hidden.另一方面,如果没有通过this.props.containerStyles我想要所有的defaultProps. 在任何情况下,styles.container应始终适用。

有没有办法用defaultProps做到这一点,或者我必须使用JavaScript逻辑,比如(伪代码(

let fancyStyleObj = {};
if(this.props.containerStyles.backgroundColor) {
fancyStyleObj.backgroundColor = this.props.containerStyles.backgroundColor 
} else { 
fancyStyleObj.backgroundColor = 'grey'
}

但是,这将绕过defaultProps因为我必须将defaultProps写入else条款。

你的方法是正确的,但你在这里做错了:

SomeComponent.defaultProps = {
backgroundColor = 'grey',
overflow: 'hidden',
};

这样,背景颜色和溢出将在this.props中可用,而不是在this.props.containerStyles中。定义containerStyles中的值。

这样写:

SomeComponent.defaultProps = {
containerStyles: {
backgroundColor: 'grey',
overflow: 'hidden',
}
};

或使用:

style={{ ...styles.container, ...this.props }}

工作示例(带this.props.containerStyles(:

class SomeComponent extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<div
style={{ ...styles.container, ...this.props.containerStyles }}>
hello
</div>
)
};
};
const styles = {
container: {
width: '50px',
height: '60px',
},
};
SomeComponent.defaultProps = {
containerStyles: {
backgroundColor: 'grey',
overflow: 'hidden',
}
};
const rootElement = document.getElementById("root");
ReactDOM.render(<SomeComponent />, rootElement);
<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>
<div id='root' />

工作示例(带this.props(:

class SomeComponent extends React.Component {
constructor(props) {
super(props);
};
render() {
return (
<div
style={{ ...styles.container, ...this.props }}>
hello
</div>
)
};
};
const styles = {
container: {
width: '50px',
height: '60px',
},
};
SomeComponent.defaultProps = {
backgroundColor: 'grey',
overflow: 'hidden',
};
const rootElement = document.getElementById("root");
ReactDOM.render(<SomeComponent />, rootElement);
<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>
<div id='root' />

最新更新