簡體   English   中英

如何從渲染函數外部引用React Component類?

[英]How to reference a React Component class from outside the render function?

我想在一個對象中引用一個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`.

我在這里做錯了什么?

自定義React組件(非常規html標簽的組件,例如h1p )必須大寫才能成為有效的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

您正在嘗試迭代一個對象數組,該對象數組將返回許多項目。 根據功能組件或類組件的反應,它應該返回單個項目。

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>
        );

    }
}

讓我們嘗試一下。

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} />
    }
}

您應該在render函數中返回組件或字符串,請嘗試...

class App extends Component {
        render() {
            return (
            <div>
              {
                GROCERIES.map((key, value) => {
                  return(<animation name={value.name}/>)
                })
              }
            </div>
            )
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM