简体   繁体   中英

How to pass class component as a functional prop in react?

Trying to send component as a prop using lambda function and TSLint throws exception.

A component can be sent as a prop like this:

<Test
  id={'XYZ-1809'}
  condn1={<Condn1Component />}
  condn2={<Condn2Component />}
/>

But when trying to send it as a functional prop, throws an error as: Lambdas are forbidden in JSX attributes due to their rendering performance impact (jsx-no-lambda)tslint(1)

<Test
  id={'XYZ-1809'}
  condn1={() => <Condn1Component />}
  condn2={() => <Condn2Component />}
/>

Condn1Component and Condn2Component can be a functional or class component that is unsure.

What's the best possible way to get rid of JSX-Lambda issue?

I managed to do this like below:

const Condn1Component = () => {
   return (<h1>I am condition1</h1>);
} 

const Condn2Component = () => {
   return (<h1>I am condition2</h1>);
} 

const condn1ComponentHandler = () => {
  return <Condn1Component />
}

const condn2ComponentHandler = () => {
  return <Condn2Component />
}

<Test
  id={'XYZ-1809'}
  condn1={condn1ComponentHandler}
  condn2={condn2ComponentHandler}
/>

And accepted as:

this.props.condn1();
this.props.condn2();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM