我有一个这样的组件
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.container
与this.props.containerStyles
和defaultProps
结合起来?想象一下,this.props.containerStyles
只有backgroundColor
,而不是overflow
。我想要defaultProps
的overflow: 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' />