如何在无状态功能组件上正确使用React.StatelessFunctionalComponent <props>?

时间:2017-09-22 12:54:06

标签: javascript flowtype

我需要为反应无状态功能组件添加流注释。 根据文档,我应该使用React.StatelessFunctionalComponent<Props>

其中包含以下签名Ref.

  

type StatelessFunctionalComponent =(props:Props)=&gt;   React.Node

但我收到了几个errors

我在这里做错了什么以及为什么?

// @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

1 个答案:

答案 0 :(得分:0)

我通过添加

找到了解决问题的方法
 const ForecastDay:React.StatelessComponent<PropsType>

并使用返回的类型ReactElement<any>React.Element<*>

&#13;
&#13;
// @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
&#13;
&#13;
&#13;