javascript - 从 React.JS 状态调用方法

标签 javascript reactjs react-dnd

我正在尝试调用 React 类中定义的“hello”方法。我对组件的支持设置为从 Students 状态对象中读取值,其中属性之一的名称为“hello”。 hello 属性是从 john 默认属性初始化的。每当 john 默认属性设置为属性以外的任何内容,并且我注销该对象时,它都会正确显示。但是当我尝试从 john 属性中调用我的“hello”方法时,没有任何反应(应该注销“hello”这个词。我的问题是,是否允许您从 React 的默认属性或 init 状态中调用方法方法?如果是这样,我是否正确实现了该模式,如果不是,我该如何修复它?

旁注:如果您想知道我正在使用的库,它是 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);

最佳答案

getDefaultProps在类(class)开始之前调用。这就是为什么它给出未定义。也许您应该将 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
    ...
   }
});

关于javascript - 从 React.JS 状态调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36974456/

相关文章:

javascript - js如何获取动态下拉菜单的选定值

reactjs - Redux 不调度 Action

reactjs - React-dnd $splice 做什么

javascript - 如果设置了参数,则将 Jquery 选项卡设置为事件状态

javascript - jQuery 下拉菜单 CSS 操作

javascript - 将样式组件 'Atoms' 嵌套在 'Molecules' 中 -> 样式/定位

javascript - 尝试在 React 中创建一个番茄钟但坚持正确传递 Prop

reactjs - React Card 示例问题 - 卡被替换而不是附加到另一列的卡列表中

javascript - 某些 IDE 的异步和等待错误

javascript - Redux:API 数据响应按点击排序