我想在一个对象中引用一个React组件,稍后将在另一个组件中进行渲染。即
class FruitAnimation extends Component {
render() {
return <div>{this.props.name}</div>
}
}
const GROCERIES = [
{
name: 'banana',
animation: FruitAnimation,
...
},
...
]
class App extends Component {
state = {
current: 'banana'
}
getGrocery = name => _.find(GROCERIES, grocery => grocery.name === name);
render() {
const { name, animation: Animation } = this.getGrocery(this.state.current);
return <Animation name={name} />
}
}
但是,我在渲染时收到此错误:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: null.
Check the render method of `App`.
我在这里做什么错了?
答案 0 :(得分:0)
自定义React组件(不是像h1
或p
这样的常规html标签的组件)必须大写才能成为有效的JSX。因此,animation
必须为Animation
:
const GROCERIES = [
{
name: 'banana',
Animation: FruitAnimation,
...
},
...
]
// ...
render() {
const { name, Animation } = this.getGrocery(this.state.current);
return <Animation name={name} />
}
更多内容:https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
答案 1 :(得分:0)
您正在尝试迭代一个对象数组,该对象数组将返回许多项目。 根据功能组件或类组件的反应,它应该返回一个项目。
class App extends Component {
state = {
current: 'banana'
}
getGrocery = name => _.find(GROCERIES, grocery => grocery.name === name);
render() {
return (
<React.Fragment>
this.getGrocery(this.state.current).map((fruit) => (
<animation name={fruit.name} />
))
</React.Fragment>
);
}
}
答案 2 :(得分:0)
让我们尝试一下。
const FruitAnimation = (name) => (
<div>{name}</div>
);
const GROCERIES = [
{
name: 'banana',
animation: FruitAnimation,
...
},
...
]
class App extends Component {
state = {
current: 'banana'
}
getGrocery = name => _.find(GROCERIES, grocery => grocery.name === name);
render() {
const { name, animation: Animation } = this.getGrocery(this.state.current);
return <Animation name={name} />
}
}
答案 3 :(得分:-1)
您应该在render函数中返回一个组件或字符串,试试这个...
class App extends Component {
render() {
return (
<div>
{
GROCERIES.map((key, value) => {
return(<animation name={value.name}/>)
})
}
</div>
)
}
}