我正在尝试调用我的 React 类中定义的“hello”方法。我在组件上的道具设置为从学生状态对象中读取值,其中一个属性名为“hello”。hello 属性是来自 john 默认属性的 init。每当 john 默认道具设置为除属性之外的任何内容时,我注销该对象时,它都会正确显示。但是当我尝试从 john 属性中调用我的“hello”方法时,什么也没有发生(它应该注销单词“hello”。我的问题是,你是否允许从 React 的默认属性或初始化状态中调用方法方法?如果是这样,我是否正确实施了该模式,如果不是,我该如何解决?
旁注:如果您想知道我正在使用的库,它是 React-Drag & Drop(用于使用 React 解耦拖放接口)
代码:
import React from 'react';
var ItemTypes = require('../box1/Constants').ItemTypes;
var DropTarget = require('react-dnd').DropTarget;
var Student = require('../box1/box1');
import update from 'react/lib/update';
require('./box2.css');
require('../../containers/Home/home.css');
var BoxSource = {
drop: function (props, monitor, component) {
const item = monitor.getItem();
console.log(item);
const delta = monitor.getDifferenceFromInitialOffset();
const left = Math.round(item.left + delta.x);
const top = Math.round(item.top + delta.y);
const id = item.id;
component.move(id, left, top);
}
};
function collect(connect, monitor) {
return {
connectDropTarget: connect.dropTarget(),
didDrop: monitor.didDrop(),
source: monitor.getSourceClientOffset(),
item: monitor.getItem(),
drop: monitor.didDrop(),
result: monitor.getDropResult()
};
}
var box2 = React.createClass({
getInitialState: function() {
return { Students: {
'1': { top: 20, left: 80, hello: this.props.john }
}
,text: 0 };
},
getDefaultProps: function() {
return {
john: this.hello
};
},
move: function(id,left,top){
this.setState(update(this.state,{
Students:{
[id]:{
$merge:{
left:left,
top: top
}
}
}
}));
},
onChange: function(e){
this.setState({ text: e.target.value });
},
add: function (e){
var StudentsNew = { };
for(var i = 1; i <= this.state.text; i++){
StudentsNew [i] = { left: 100, top: 100 } ;
}
var StudentsCopy = this.state.Students;
var studentMerge = Object.assign(StudentsCopy,StudentsNew);
this.setState({ Students: studentMerge })
},
reset: function(){
this.setState({ Students:{ [1]: { top: 20, left: 80 } } });
},
hello: function(){
console.log('hello');
},
render:function() {
const { Students } = this.state;
var connectDropTarget = this.props.connectDropTarget;
return connectDropTarget(
<div id = "box">
{Object.keys(Students).map(key =>{
const { left, top, title, hello } = Students[key];
return(
<div>
<Student key = {key} id = {key} left = {left}
top = {top} hello = {hello} > </Student>
</div>
);})}
<button onClick = {this.add}> Enter Amount of Students </button>
<button onClick = {this.reset}> Reset </button>
<input onChange = {this.onChange} type="number" name="quantity" min="1" max="200"/><br/>
</div>
);
}
});
module.exports = DropTarget(ItemTypes.STUDENT, BoxSource, collect)(box2);