React-ClickDrag子组件回调

时间:2016-05-15 10:27:14

标签: javascript svg reactjs

我已经对svg组件做出反应,该组件有2个使用react-clickdrag

的孩子

我尝试将回调函数从父级传递给要在拖动时调用的子组件。回调函数在拖动时按预期调用,但this变量返回子组件而不是回调函数中的父组件。

我是否错误地构建了某些内容?或者是react-clickdrag以某种方式修改this变量?

父组件:

import React from 'react';
import Bar from './Bar.jsx';
import Node from './Node.jsx';

class TimeSpan extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      xPos: this.props.xPos,
      yPos: this.props.yPos,
      length: this.props.length
    };
  }

  changeStartPos(diffPos) {
    console.log(this); //returns child component
    this.setState({xPos: this.state.xPos + diffPos, length: this.state.length + diffPos});
  }

  changeEndPos(diffPos) {
    console.log(this); //returns child component
    this.setState({length: this.state.length + diffPos});
  }

  render() {
    return (
      <g>
        <Node changePos={this.changeStartPos} xPos={this.state.xPos} yPos={this.state.yPos} radius={10} />
        <Node changePos={this.changeEndPos} xPos={this.state.xPos + this.state.length} yPos={this.state.yPos} radius={10} />
      </g>
    );
  }

}

export default TimeSpan;

子组件:

import React from 'react';
import clickDrag from 'react-clickdrag';

class NodeComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
        lastPositionX: 0,
        lastPositionY: 0,
        currentX: this.props.xPos,
        currentY: this.props.yPos
    };
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.dataDrag.isMoving) {
        this.props.changePos(nextProps.dataDrag.moveDeltaX);
    }
  }

  render() {
    return (
      <circle cx={this.props.xPos} cy={this.props.yPos} r={this.props.radius} fill="black" />
    );
  }

}

var Node = clickDrag(NodeComponent, {touch: true});

export default Node;

指数:

import React from 'react';
import {render} from 'react-dom';
import TimeSpan from './TimeSpan.jsx';

class App extends React.Component {
  render () {
    return (
      <svg style={{postion:'fixed', top: 0, left: 0, width: '100%', height: '100%'}}>
        <TimeSpan xPos={300} yPos={300} length={300} />
      </svg>
    );
  }
}

render(<App/>, $('#app')[0]);
<html>
  <head>
    <meta charset="utf-8">
    <title>React.js using NPM, Babel6 and Webpack</title>
    <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
    <style>
      html, body { margin:0; padding:0; overflow:hidden }
    </style>
  </head>
  <body>
    <div id="app" />
    <script src="public/bundle.js" type="text/javascript"></script>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

使用ES6语法,您的函数不会像使用React.createClass时那样自动绑定,因此您必须明确绑定它们。

执行此操作的最佳位置是constructor,因此只会发生一次。

constructor(props) {
    super(props);
    this.changeStartPos = this.changeStartPos.bind(this);
    ...
}