首页 > 解决方案 > 如何从渲染函数外部引用 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`.

我在这里做错了什么?

标签: javascriptreactjs

解决方案


自定义 React 组件(不是常规 html 标签的组件,如h1or 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


推荐阅读