gpt4 book ai didi

javascript - 将类对象传递给 ReactJS 组件

转载 作者:行者123 更新时间:2023-11-29 19:14:41 24 4
gpt4 key购买 nike

我收到以下错误:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. 

我也从 React 收到这个警告:

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).

我遇到的实际问题(正如我通过调试了解到的)是我不能将类作为参数传递,如下所示:<BigCard pokemon={result} /> ,因为这里的结果是类的一个对象。我应该怎么做才能使其正常工作。是否有将类作为参数传递的最佳实践?

我有这个组件:

export var BigCard = React.createClass({
render: function() {
var rows = [];
var pokemon = this.props.pokemon;
for (var variable in pokemon) {
if (pokemon.hasOwnProperty(variable) && variable.toString() !== 'id' && variable.toString !== 'name' && variable.toString !== 'image' && variable.toString !== 'types') {
rows.push(
<tr>
<td class='mdl-data-table__cell--non-numeric'>
{variable}
</td>
<td>
{pokemon[variable]}
</td>
</tr>
)
}
}
return (
<div class='mdl-card mdl-shadow--4dp'>
<div class='mdl-card__title'>
<img src={pokemon.image.src} alt='Pokemon' class='bigCard__img'/>
</div>
<h2 class='mdl-card__title-text'></h2>
<div class='mdl-card__supporting-text'>
<table class='mdl-data-table mdl-js-data-table'>
<thead>
<tr>
<th class='mdl-data-table__cell--non-numeric'>Type</th>
<th class='mdl-data-table__cell--non-numeric'>{pokemon.types}</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
</div>
);
}
});

我有以下代码,我想运行:

import React from 'react';
import ReactDOM from 'react-dom';
import * as DataLogic from './modules/data-logic.js';
import SmallCard from './components/SmallCard.jsx';
import BigCard from './components/BigCard.jsx';

DataLogic.getPokemonById(3).then((result) => {
ReactDOM.render(
<BigCard pokemon={result} />,
document.getElementById('bigCard')
);
}).catch((error) => console.log(`${error} in main.js`));

getPokemonById 的结果是 DetailedPokemon 类的对象。这是我的类,用作 View 模型:

export default class DetailedPokemon {
constructor(id, name, image, types, attack, defense, hp, spAttack, spDefense, speed, weight, totalMoves) {
this.id = id;
this.name = name;
this.image = image;
this.types = types;
this.attack = attack;
this.defense = defense;
this.hp = hp;
this.spAttack = spAttack;
this.spDefense = spDefense;
this.speed = speed;
this.weight = weight;
this.totalMoves = totalMoves;
}
}

我希望,我已经清楚地解释了一切。你能帮我解决我的问题吗?

最佳答案

您错误地导入 BigCard,也许还有 SmallCard。

当您使用 export foo = 'bar' 导出内容时,foo 会使用大括号导入:import {foo} from './fooFile'.

如果您想使用import foo from ./fooFile 导入,fooFile 必须导出一个默认值:export default const BigCard = React.createClass(...

这应该会处理好它。

关于javascript - 将类对象传递给 ReactJS 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36271651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com