@rmnuts
Frontend-developer

Как правильно использовать React и Flow с синтаксисом ES6?

Пытаюсь использовать React и Flow с синтаксисом ES6 и получаю ошибку:
line 9 col 3 React element: Hello - Error:

в файле app.jsx:
/* @flow */
var React = require('react');
var Hello = require('../src/components_flow/hello/hello');

//var Input = require('../src/components_flow/input/input');
//React.renderComponent(<Hello name="World" />, document.getElementById('react-container'));

React.render(
  <Hello name="World"/>,
  document.getElementById('react-container'));


hello.jsx:
/* @flow */

var React = require('react');

class Hello extends React.Component {
  render(): any {
    return <div>Hello {this.props.name}</div>;
  }
}

module.exports = Hello;


gulp task:
gulp.task('react', function () {
    return gulp.src([
      './src/components_flow/hello/hello.jsx',
      './src/components_flow/input/input.jsx',
      './src/app.jsx'],
      function (er, files) {
          // files is an array of filenames.
          // If the `nonull` option is set, and nothing
          // was found, then files is ["**/*.js"]
          // er is an error object or null.
          //console.log(files);
        })
        .pipe(flow({
            all: false,
            weak: false,
            killFlow: false,
            beep: false,
            abort: false //abort the gulp task after the first Typecheck error
        }))
        .pipe(react({stripTypes: true, harmony: true}))       
        .pipe(gulp.dest(function(file) {
          return file.base;
    }));
});


Подробности в данной ветке репозитория: https://github.com/RinatMullayanov/react-typescrip...
Чтобы увидеть данную ошибку в консоли нужно набрать:
gulp react

После некоторого гугления я к пришел к тому что для того чтобы ошибка исчезла писать нужно примерно так:
/* @flow */

var React = require('react');

type HelloProps = {
  name: string
};

class Hello extends React.Component {
  static propTypes: { name: string };
  static defaultProps: { name: string };
 
  constructor(props: HelloProps) {
     super(props);
  }

  render(): any {
    return <div>Hello {this.props.name}</div>;
  }
}


module.exports = Hello;

И это работает.
Объясните, пожалуйста, почему так нужно делать(почему требуется объявлять propTypes и defaultProps)?
Это какие-то тонкости реализации поддержки ES6 в React?
  • Вопрос задан
  • 1865 просмотров
Пригласить эксперта
Ответы на вопрос 1
art1z
@art1z
Программист-многостаночник в EffectiveSoft
Почитайте для чего нужен flowtype.org (A STATIC TYPE CHECKER FOR JAVASCRIPT)
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы