首页 > 解决方案 > 如何使用扩展运算符使用作为道具传递的函数

问题描述

如何使用 React 中使用扩展运算符作为道具传递的另一个组件中的单个函数。

const Component=(props)=>
{
  const A=()=>  
   {  
    }
  const B=()=>
    {
    }
  render(){
         return(
                <Anothercomponent RenderChild={(props)=>{<Component {...props} />}}
                );
          }
 }


const Anothercomponent=()=>
   {
       render(){
       const {RenderChild} = this.props;
       return(

                 //how to consume function A here
              );
    } 

标签: reactjs

解决方案


首先,你还没有通过 functionABas props

其次,您正在使用功能组件,因此您可以从函数参数而不是this.props. 它还需要使用渲染方法。如果使用渲染,则需要将组件定义为类组件

const Anothercomponent=(props)=> {
    const { RenderChild } = props;
    return(
        <div>Another component</div>
    );
}

const Component=(props)=> {
   const A=()=> {}
   const B=()=> {}
   return(
        <Anothercomponent RenderChild={(props)=>{<Component {...props} />}}
  );
}

推荐阅读