2016-05-15 5 views
0

私はドラッグで呼び出される子コンポーネントに親からコールバック関数を渡ししようとしているreact-clickdragリアクト-ClickDrag子コンポーネントのコールバックを

を使用する2人の子供を持つSVGコンポーネントを反応させてきました。コールバック関数はドラッグ時に期待どおりに呼び出されますが、this変数はコールバック関数の親コンポーネントではなく子コンポーネントを返します。

構造が正しくありませんか?または、何らかの形で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]); 
012 ES6で
<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

あなたが明示的にバインドする必要がありますので、React.createClassを使用するとき、彼らはしているようなあなたの機能が自動的にバインドされることはありません構文。

これを実行する最適な場所はconstructorであるため、一度だけ発生します。

constructor(props) { 
    super(props); 
    this.changeStartPos = this.changeStartPos.bind(this); 
    ... 
} 
関連する問題