如何正确创建并渲染React函数式组件?解决代码报错问题
正确创建并渲染React函数式组件的方法
你遇到的问题根源在于在类组件的class体内直接声明函数组件是无效的JavaScript类语法——类的内部只能定义类方法、构造函数,不能直接嵌套function声明或者裸函数定义。下面给你几种正确的实现方式:
方式一:独立定义函数式组件(最推荐)
把函数式组件和类组件分开定义,放在类的外部,这样两者都是独立的可复用组件,代码结构更清晰:
// 先定义独立的函数式组件 function OtherComponent(props) { return ( <div> {props.text} </div> ); } // 再定义你的类组件 class MyComponent extends React.Component { render() { return ( <div> <OtherComponent text="test" /> {/* 直接引用外部定义的组件 */} </div> ); } }
这种方式是React开发中最常用的,函数式组件可以被多个父组件复用,也方便单独测试。
方式二:在类组件的render方法内定义(仅限当前组件内部使用)
如果你希望函数式组件只在MyComponent内部使用,可以把它定义在render方法里面:
class MyComponent extends React.Component { render() { // 在render内部定义函数式组件(用箭头函数或函数表达式) const OtherComponent = (props) => { return ( <div> {props.text} </div> ); }; return ( <div> <OtherComponent text="test" /> </div> ); } }
注意这里要用const/let声明组件,每次render执行时都会重新创建这个组件,适合简单的内部组件,复杂组件推荐用第一种方式避免性能损耗。
方式三:作为类的实例属性定义
也可以把函数式组件作为类的实例属性,用箭头函数声明:
class MyComponent extends React.Component { // 定义为类的实例属性 OtherComponent = (props) => { return ( <div> {props.text} </div> ); }; render() { return ( <div> {/* 引用时需要加this. */} <this.OtherComponent text="test" /> </div> ); } }
这种方式组件只会在类实例化时创建一次,性能比render内定义好,但同样只能在当前类组件内部使用。
为什么你的尝试会报错?
- 最初在class体内直接写
function OtherComponent(props) { ... }:违反了JavaScript类的语法规则,类内部不允许这样的函数声明,所以引擎抛出Unexpected token错误。 - 移除
function关键字后变成OtherComponent(props) { ... }:这在类里也不是有效的语法(类方法的正确写法是OtherComponent() { ... },但这是类方法而非组件),所以会提示OtherComponent is not defined。
另外,现在React更推荐使用函数式组件配合Hooks,如果你不需要类组件的特性(比如类式状态管理、旧版生命周期),甚至可以把MyComponent也改成函数式组件:
function OtherComponent(props) { return <div> {props.text} </div>; } function MyComponent() { return ( <div> <OtherComponent text="test" /> </div> ); }
内容的提问来源于stack exchange,提问作者Abe Miessler
相关产品推荐
相关产品推荐

