【问题标题】:can't get props from child component in react在反应中无法从子组件中获取道具
【发布时间】:2020-04-07 14:46:34
【问题描述】:

在反应组件中使用 html 拖放 api 时,我有一个子组件传递了道具。我正在尝试将孩子的“类型”道具记录到控制台,但我无法使用 card.type 访问它

如果我将“卡片”记录到控制台,我会得到以下信息:

<div type="allowed2" id="item-2" class="card" draggable="true" style="display: none;">
  <p>card 2</p>
</div>

这是我当前的代码和我尝试阅读道具:

const drop = (e) => {
  e.preventDefault();
  const card_id = e.dataTransfer.getData('item_id');
  const card = document.getElementById(card_id);

  let i = 0;
  let count = 0;
  for (i in props.allowedtypes){
    console.log(card);

    if (props.allowedtypes[i] !== card.type){ //need to check the card.type against my allowed types
      count++;
    }

    if (count === props.allowedtypes.length){
      alert('sorry that file type is not accepted');
      return;
    }

    i++;
  }

  e.target.appendChild(card);
}

const dragOver = e => {
  e.preventDefault();

  return (
    <div id={props.id} onDrop={drop} onDragOver={dragOver} className = {props.className} allowedtypes={props.allowedTypes}>
      {props.children}
    </div>
  );
}

也许有人可以对此有所了解?也许我没有以某种方式从 react.children 正确读取道具。

【问题讨论】:

    标签: reactjs children react-props


    【解决方案1】:

    您正在将其记录到控制台,因为使用函数 document.getElementById 返回一个 HTMLElement,而不是一个 React 组件。 React 组件实际上并不存在于 DOM 中,而是呈现给 HTML 元素。您可以尝试这样做:card.getAttribute('type') 以获取结果 divtype 属性

    【讨论】:

      猜你喜欢
      • 2016-08-20
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多