从React调用方法.JS州

Calling Method From a React.JS State

本文关键字:JS 方法 调用 React      更新时间:2023-09-26

我正在尝试调用React类中定义的"hello"方法。我在组件上的道具被设置为读取Students状态对象中的值,其中一个属性的名称为"hello"。hello属性是来自john默认属性的init。每当john默认道具被设置为除属性之外的任何属性,并且我注销了该对象时,它就会正确显示。但是,当我尝试从john属性中调用我的"hello"方法时,什么都没有发生(它应该注销单词"hello"。我的问题是,你可以从React的默认属性或init状态方法中调用方法吗?如果是,我是否正确地实现了模式,如果不是,我该如何修复它?

旁注:如果你想知道我正在使用的库,那就是ReactDrag&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);

getDefaultProps在类启动之前被调用。这就是它给出undefined的原因。也许您应该将hello方法称为getInitialState 中的状态

编辑将方法设置为状态的示例:

var example = React.createClass({
getInitialState: function(){
    return {
        methodName : this.hello
    }
},
hello: function(){
    console.log('hello');
},
render: function(){
    console.log(this.state.methodName); // call or pass it to a child
    ...
   }
});