在单独的文件中访问react组件的props

时间:2015-12-04 17:50:09

标签: javascript reactjs

我有两个反应组件必须保留在单独的文件中,但需要共享一个属性。一个组件将更改this.props.color,另一个组件需要知道新颜色是什么。我知道你可以导入实际的组件,但我不知道如何从该组件访问属性。这是我的应用程序的一个非常简单的例子(我正在使用ES6)

component1.js

import React, {Component, PropTypes} from 'react';

export default class FirstComponent extends Component {
  static propTypes = {
    color: PropTypes.string
  }
  handleClick () {
    //change color here
  }
  render () {
    var styles = {
      backgroundColor: this.props.color
    };
    return <div id="one" style={styles} onclick={this.handleClick}></div>;
  }
}

component2.js

import React, {Component} from 'react';
import FirstComponent from './component1.js';

export default class SecondComponent extends Component {
  /*...*/
  render () {
    console.log(FirstComponent); //??
    return <div id="two"></div>;
  }
}

parent1.js

import React, {Component} from 'react';
import FirstComponent from './component1.js';

export default class FirstComponentParent extends Component {
  color = 'rgb(255, 0, 0)';
  return React.createElement(FirstComponent, {color: this.color});
}

parent2.js

import React, {Component} from 'react';
import SecondComponent from './component2.js';

export default class SecondComponentParent extends Component {
  return React.createElement(SecondComponent);
}

1 个答案:

答案 0 :(得分:0)

使用公共父组件并将颜色作为prop传递给第二个组件,并传递一种方法,将颜色作为prop添加到第一个组件。

&#13;
&#13;
import React, {Component, PropTypes} from 'react';

export default class FirstComponent extends Component {
  constructor() {
    super();
    this.state = {color: 'black'};
  }
  handleClick () {
    //change color here
    this.props.changeColor(newColor);
  }
  render () {
    var styles = {
      backgroundColor: this.state.color
    };
    return <div id="one" style={styles} onclick={this.handleClick}></div>;
  }
}
&#13;
&#13;
&#13;

&#13;
&#13;
import React, {Component, PropTypes} from 'react';

export default class SecondComponent extends Component {
  render () {
    var styles = {
      backgroundColor: this.props.color
    };
    return <div id="one" style={styles}></div>;
  }
}
&#13;
&#13;
&#13;

&#13;
&#13;
import React, {Component, PropTypes} from 'react';
import FirstComponent from './first';
import SecondComponent from './second';

export default class ParentComponent extends Component {
  constructor() {
    super();
    this.state = {firstColor: 'black'};
  }
  changeColor = (newColor) => {
    this.setState({firstColor: newColor});
  }
  render () {
    return (
      <div>
        <FirstComponent changeColor={this.changeColor}/>
        <SecondComponent color={this.state.firstColor}/>
      </div>;
    )
  }
}
&#13;
&#13;
&#13;