如何向作为Prop传入的组件传递Props?React报错解决
这个报错的原因很明确——你传给Fruits组件的component prop是一个已经实例化的React元素(<Fruit />),而不是一个可调用的组件函数或类。当Fruits里尝试把它当作函数调用component({ fruit })时,自然会抛出"component is not a function"的错误。
下面是两种可行的解决方法,推荐第一种,更符合React组件复用的常规实践:
方法一:传递组件本身而非组件实例
你需要把Fruit组件(而不是<Fruit />元素)传给Fruits,然后在Fruits里将其作为自定义组件渲染,同时传递所需的props。另外还要修正一个小问题:你的Fruit组件里用了fruit.name,但数据源里的字段是text,这会导致渲染出undefined,需要一并修正。
修正后的完整代码:
import React from 'react' const fruits = [ { id: 1, text: `mango` }, { id: 2, text: `apple` }, ] // 修正字段名:fruit.text 代替 fruit.name const Fruit = ({ fruit }) => ( <div>{ fruit.id } - { fruit.text }</div> ) const Fruits = ({ component: Component }) => ( <ul> {/* 把component重命名为Component(React约定组件首字母大写),用JSX渲染并传递props,同时添加key */} { fruits.map( fruit => <li key={fruit.id}><Component fruit={fruit} /></li> ) } </ul> ) export const Parent = () => ( <div> {/* 传递Fruit组件本身,而不是<Fruit />元素 */} <Fruits component={ Fruit } /> </div> )
这里的关键改动:
- 在
Parent中,传递Fruit(组件构造函数)而非<Fruit />(已创建的元素) - 在
Fruits中,把component重命名为Component(React要求组件名称首字母大写,否则会被当作普通HTML标签处理) - 使用JSX语法
<Component fruit={fruit} />渲染组件,而不是尝试调用它 - 添加了
key属性,这是React列表渲染的必填项,避免警告 - 修正了
Fruit组件中字段名的错误
方法二:传递渲染函数
如果你更倾向于使用渲染函数的方式,也可以把component prop定义为一个接收props并返回React元素的函数:
import React from 'react' const fruits = [ { id: 1, text: `mango` }, { id: 2, text: `apple` }, ] const Fruit = ({ fruit }) => ( <div>{ fruit.id } - { fruit.text }</div> ) const Fruits = ({ component }) => ( <ul> {/* 直接调用渲染函数,传递fruit props */} { fruits.map( fruit => <li key={fruit.id}>{ component({ fruit }) }</li> ) } </ul> ) export const Parent = () => ( <div> {/* 传递一个渲染函数,接收props并返回Fruit组件 */} <Fruits component={ ({ fruit }) => <Fruit fruit={fruit} /> } /> </div> )
这种方式也能解决问题,但相比第一种传递组件的方式,代码稍显繁琐,适合需要额外处理props的场景。
内容的提问来源于stack exchange,提问作者anonym
相关产品推荐
相关产品推荐

