Javascript Reactjs-将颜色作为道具传递
我正在尝试使用颜色作为设置中的道具。在General_heading组件中,我希望能够传递一个道具来定义标题的颜色,但目前无法让它响应。思想? 在app.js中:Javascript Reactjs-将颜色作为道具传递,javascript,reactjs,react-props,Javascript,Reactjs,React Props,我正在尝试使用颜色作为设置中的道具。在General_heading组件中,我希望能够传递一个道具来定义标题的颜色,但目前无法让它响应。思想? 在app.js中: <div><General_header theme_color="red"/></div> 通常,_header.js: import React, { Component } from 'react'; class General_header extends React.Component
<div><General_header theme_color="red"/></div>
通常,_header.js:
import React, { Component } from 'react';
class General_header extends React.Component {
constructor(props) {
super(props);
this.state = {logo_img: props.logo_img,
theme_color: props.theme_color};
}
render() {
return (
<div style={[styles.header,{backgroundColor:this.state.theme_color}]}>test
<img src={this.state.logo_img} alt={'logo'} style={styles.logo_img} />
</div>
);
}
}
var styles = {
header: {
height: '100px',
display: 'block'},
logo_img: {
height: '40px',
display: 'inline-block'}
}
export default General_header;
用例
看看这个
对您的代码进行了以下更改:
class General_header extends React.Component {
render() {
// This will create a single object containing fields
// from styles.header plus the extra backgroundColor field.
const fullStyle = {
...styles.header, // This is called the spread operator
backgroundColor: this.props.theme_color // No need to assign this to state
}
return (
<div style={fullStyle}>test
<img src={this.state.logo_img} alt={'logo'} style={styles.logo_img} />
</div>
);
}
}
非常需要修复,但仍无法正常运行。这条线似乎有点断裂:当只存在一个样式元素或另一个样式元素时,它可以工作,但当数组中同时存在这两个样式元素时,它们似乎都不起作用。有什么想法吗?使用style={{backgroundColor:this.state.themeColor}}这种方法的问题是,无论何时在没有卸载组件的情况下更新道具,重新装载后,您的状态都不会更新。我建议检查componentWillReceiveProps生命周期方法,或者如果您使用的是16.3+那么getDerivedStateFromProps。如果我没有弄错的话,默认组件上的样式属性必须是null/未定义或对象。
class General_header extends React.Component {
render() {
// This will create a single object containing fields
// from styles.header plus the extra backgroundColor field.
const fullStyle = {
...styles.header, // This is called the spread operator
backgroundColor: this.props.theme_color // No need to assign this to state
}
return (
<div style={fullStyle}>test
<img src={this.state.logo_img} alt={'logo'} style={styles.logo_img} />
</div>
);
}
}
var fullStyle = Object.assign(
{},
styles.header,
{ backgroundColor: this.props.theme_color }
);