【问题标题】:React 0.14-RC-1 -- OnMouseEnter & OnMouseLeave -- Change state / styleReact 0.14-RC-1 -- OnMouseEnter 和 OnMouseLeave -- 更改状态/样式
【发布时间】:2015-10-08 23:33:49
【问题描述】:

我正在尝试根据 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:无法读取 undefined(...) 的属性“状态”

【问题讨论】:

    标签: d3.js reactjs


    【解决方案1】:

    我看到一个问题是需要传入“this”。另一个更改可能是可选的。

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

    【讨论】:

    • 错误消失了,但它没有影响事件函数。
    猜你喜欢
    • 2021-06-20
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2019-04-17
    • 2017-12-28
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多