Reactjs - 将颜色作为道具传递

时间:2018-05-09 22:07:18

标签: javascript reactjs react-props

我正试图在reactjs设置中使用颜色作为道具。在General_heading组件中,我希望能够传递一个prop来定义标题的颜色,但我目前无法响应它。思考? 在app.js中:

<div><General_header theme_color="red"/></div>

在General_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;

2 个答案:

答案 0 :(得分:1)

使用camelCase

看看这个https://github.com/airbnb/javascript/tree/master/react#naming

<GeneralHeader themeColor="red"/>


constructor(props) {
   super(props);
   this.state = {
      logoImg: props.logoImg,
     themeColor: props.themeColor
   };
}

<div style={{backgroundColor: this.state.themeColor}}>

答案 1 :(得分:0)

在您的代码下面做了一些更改:

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>
    );
  }
}

ES5版本:

var fullStyle = Object.assign(
  {}, 
  styles.header, 
  { backgroundColor: this.props.theme_color }
);