简体   繁体   中英

How to properly use React.StatelessFunctionalComponent<Props> on a stateless functional component?

I need to add flow annotation for a react stateless functional component. Accordingly to docs I should use React.StatelessFunctionalComponent<Props>

Which has the following signature Ref. :

type StatelessFunctionalComponent = (props: Props) => React.Node

But I receive several errors .

What am I doing wrong here and why?

 // @flow import * as React from 'react' import moment from 'moment' import IconWeather from '../../shared/icon/IconWeather' /* eslint-disable no-undef */ type PropsType = { +date: number, +tempMin: number, +tempMax: number, +iconCode:number, +weatherDescription:string } /* eslint-enable no-undef */ const ForecastDay = ({ date, tempMin, tempMax, iconCode, weatherDescription }:PropsType):React.StatelessFunctionalComponent<PropsType> => { const dateFormat = moment.unix(date).format('ddd, MMM D') const tempMinRounded = Math.round(tempMin) const tempMaxRounded = Math.round(tempMax) return ( <div> <div>{dateFormat}</div> <div> <IconWeather code={iconCode} /> </div> <div> <div> {tempMinRounded}&#176; </div> <div> {tempMaxRounded}&#176; </div> </div> <div> {weatherDescription} </div> </div> ) } export default ForecastDay 

I found a solution to my problem by adding

 const ForecastDay:React.StatelessComponent<PropsType>

and use as returned type ReactElement<any> or React.Element<*> .

 // @flow import * as React from 'react' import moment from 'moment' import IconWeather from '../../shared/icon/IconWeather' /* eslint-disable no-undef */ type PropsType = { +date: number, +tempMin: number, +tempMax: number, +iconCode:number, +weatherDescription:string } /* eslint-enable no-undef */ const ForecastDay:React.StatelessComponent<PropsType> = ({ date, tempMin, tempMax, iconCode, weatherDescription }:PropsType):ReactElement<any> => { const dateFormat = moment.unix(date).format('ddd, MMM D') const tempMinRounded = Math.round(tempMin) const tempMaxRounded = Math.round(tempMax) return ( <div> <div>{dateFormat}</div> <div> <IconWeather code={iconCode} /> </div> <div> <div> {tempMinRounded}&#176; </div> <div> {tempMaxRounded}&#176; </div> </div> <div> {weatherDescription} </div> </div> ) } export default ForecastDay 

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