React ClickDrag子组件回调
React-ClickDrag Child Component Callbacks
我有一个react svg组件,它有两个使用react clickdrag 的子组件
我正在尝试将回调函数从父组件传递给子组件,以便在拖动时调用。回调函数在拖动时按预期调用,但this
变量返回回调函数中的子组件,而不是父组件。
我是不是有什么结构不正确?还是react点击拖动以某种方式修改了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>
使用ES6语法,函数不会像使用React.createClass
时那样自动绑定,因此必须显式绑定它们。
这样做的最佳位置是在constructor
中,因此它只发生一次。
constructor(props) {
super(props);
this.changeStartPos = this.changeStartPos.bind(this);
...
}
相关文章:
- React ClickDrag子组件回调
- 在foreach中加载所有项后,Knockoutjs组件回调
- 反应.js:将回调传递给子组件并删除组件
- React.js如何将回调传递给子组件
- 如何绑定'这'到react类之外的函数,后者是来自其他组件的回调
- 如何获取 Ember 组件对象内部承诺成功或错误回调
- 将数据从回调传递到 React 组件
- 如何在回调函数的 Angular 1.5 组件中处理这个问题
- 如何使用 Flux+React.js 从数据库回调渲染组件
- 反应组件 JSON 回调范围
- 角度组件语法,回调函数使用错误的上下文调用
- 如何从WebSocket回调访问React中的组件方法
- 如何获取模型内部的组件引用保存回调函数
- 处理多个组件实例的回调
- onChange回调未在React组件中启动
- 如何在$.ajax的回调函数中更改组件视图中的变量
- -父组件回调如何通过子道具接收参数顺序/值
- 如果不在主代码流中,ActiveX组件调用的回调函数不会触发
- 如何用第三方组件和回调测试EmberJS ?
- 希望通过一个回调函数与参数的子组件在聚合物