React 0.14-RC-1 - OnMouseEnter& OnMouseLeave - 更改状态/样式

时间:2015-10-08 14:22:30

标签: d3.js reactjs

  

我正在尝试更改元素的不透明度,每个mouseEnter和mouseLeave事件:

import React, { Component, PropTypes } from 'react';
import d3 from 'd3';
import Bar from './Bar';
import lodash from 'lodash';
export default class DataSeries extends Component {

  static propTypes = {
    availableHeight: PropTypes.number,
    data: PropTypes.array,
    height: PropTypes.number,
    offset: PropTypes.number,
    width: PropTypes.number
  }
  constructor() {
    super();
    this.state = ({
      opacity: 1
    });
  }
  onMouseEnterHandler() {
    this.setState({ opacity: 0.5 });
  }

  onMouseLeaveHandler() {
    this.setState({ opacity: 1 });
  }
  render() {
    const props = this.props;
    const yScale = d3.scale.linear()
      .domain([0, d3.max(this.props.data)])
      .range([0, this.props.height]);

    const xScale = d3.scale.ordinal()
      .domain(d3.range(this.props.data.length))
      .rangeRoundBands([0, this.props.width], 0.05);

    const colors = d3.scale.linear()
      .domain([0, this.props.data.length])
      .range(['#FFB832', '#C61C6F']);

    const bars = lodash.map(this.props.data, function(point, index) {
      return (
        <Bar height={ yScale(point) } width={ xScale.rangeBand() }
                  offset={ xScale(index) } availableHeight={ props.height }
                  color={ colors(point) } key={ index }
                  onMouseEnter={ () => this.onMouseEnterHandler() }
                  onMouseLeave={ () => this.onMouseLeaveHandler() }
                  style = { { opacity: this.state.opacity } } <-- error points here
        />
      );
    });
    return (
      <g>{ bars }</g>
    );
  }
}
DataSeries.defaultPropTypes = {
  title: '',
  data: []
};
  

我收到错误:

     

TypeError:无法读取属性&#39; state&#39;未定义的(...)

1 个答案:

答案 0 :(得分:0)

我看到一个问题是“这个”需要传入。另一个变化可能是可选的。

    let vm = this;
    let bars = lodash.map(this.props.data, function(point, index, vm) {
        let opacity = { opacity: vm.state.opacity };
        return (
            <Bar height={ yScale(point) } width={ xScale.rangeBand() }
                                offset={ xScale(index) } availableHeight={ props.height }
                                color={ colors(point) } key={ index }
                                onMouseEnter={ vm.onMouseEnterHandler }
                                onMouseLeave={ vm.onMouseLeaveHandler }
                                style = { opacity }
            />
        );
    });