javascript - 如何从渲染函数外部引用 React 组件类?
问题描述
我想在一个对象中引用一个 React 组件,稍后我将使用它在另一个组件中进行渲染。IE,
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`.
我在这里做错了什么?
解决方案
自定义 React 组件(不是常规 html 标签的组件,如h1
or p
)必须大写才能成为有效的 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
推荐阅读
- reactjs - 登录功能 React Js
- jmeter - 图表侦听器 Jmeter Remote
- c - 在 C 语言中找到 'e' 的近似值
- ruby-on-rails - Chartkick on rails:根据数据改变图表样式
- javascript - Kendo Treeview - 将类添加到 treeItem
- 剑道树视图中的元素
- ruby-on-rails - 将 ruby 中间件导出到 node.js
- sql - 带有布尔值和排序的 SQL 语句
- r - 在 R 中子集数据帧后拆分的奇怪行为
- android - OpenGL ES 2.0 圆形纹理在混合时具有可见轮廓
- javascript - 具有固定标题和可变列宽的反应虚拟化网格