2017-09-25 3 views
0

나는 새로운 반응을 보이며 새로운 프로젝트를 진행합니다. React Autosuggest 모듈을 사용해야하지만, ES6에서는 그 예입니다.React-Autosuggest and ES5

사람은

function states() { 
    return [ 
    {abbr: 'AL', name: 'Alabama'}, 
    {abbr: 'AK', name: 'Alaska'}, 
    {abbr: 'AZ', name: 'Arizona'}, 
    {abbr: 'AR', name: 'Arkansas'}, 
    ] 
} 

class AutocompleteExample extends React.Component { 
    constructor() { 
    super() 
    this.state = {tags: []} 
    } 

    handleChange (tags) { 
    this.setState({tags}) 
    } 

    render() { 
    function autocompleteRenderInput ({addTag, ...props}) { 
     const handleOnChange = (e, {newValue, method}) => { 
     if (method === 'enter') { 
      e.preventDefault() 
     } else { 
      props.onChange(e) 
     } 
     } 

     const inputValue = (props.value && props.value.trim().toLowerCase()) || '' 
     const inputLength = inputValue.length 

     let suggestions = states().filter((state) => { 
     return state.name.toLowerCase().slice(0, inputLength) === inputValue 
     }) 

     return (
     <Autosuggest 
      ref={props.ref} 
      suggestions={suggestions} 
      shouldRenderSuggestions={(value) => value && value.trim().length > 0} 
      getSuggestionValue={(suggestion) => suggestion.name} 
      renderSuggestion={(suggestion) => <span>{suggestion.name}</span>} 
      inputProps={{...props, onChange: handleOnChange}} 
      onSuggestionSelected={(e, {suggestion}) => { 
      addTag(suggestion.name) 
      }} 
      onSuggestionsClearRequested={() => {}} 
      onSuggestionsFetchRequested={() => {}} 
     /> 
    ) 
    } 

    return <TagsInput renderInput={autocompleteRenderInput} value={this.state.tags} onChange={::this.handleChange} /> 
    } 
} 

답변

1

당신은 당신의 코드를 transpile하기 위해 바벨을 사용하시기 바랍니다 ES5을 번역 할 수 있습니다. 이 작업을 수행하려면 babel repl을 사용할 수 있습니다. 코드의 번역 된 버전은 다음과 같습니다

'use strict'; 

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 

var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } 

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } 

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } 

function states() { 
    return [{ abbr: 'AL', name: 'Alabama' }, { abbr: 'AK', name: 'Alaska' }, { abbr: 'AZ', name: 'Arizona' }, { abbr: 'AR', name: 'Arkansas' }]; 
} 

var AutocompleteExample = function (_React$Component) { 
    _inherits(AutocompleteExample, _React$Component); 

    function AutocompleteExample() { 
    _classCallCheck(this, AutocompleteExample); 

    var _this = _possibleConstructorReturn(this, (AutocompleteExample.__proto__ || Object.getPrototypeOf(AutocompleteExample)).call(this)); 

    _this.state = { tags: [] }; 
    return _this; 
    } 

    _createClass(AutocompleteExample, [{ 
    key: 'handleChange', 
    value: function handleChange(tags) { 
     this.setState({ tags: tags }); 
    } 
    }, { 
    key: 'render', 
    value: function render() { 
     function autocompleteRenderInput(_ref) { 
     var addTag = _ref.addTag, 
      props = _objectWithoutProperties(_ref, ['addTag']); 

     var handleOnChange = function handleOnChange(e, _ref2) { 
      var newValue = _ref2.newValue, 
       method = _ref2.method; 

      if (method === 'enter') { 
      e.preventDefault(); 
      } else { 
      props.onChange(e); 
      } 
     }; 

     var inputValue = props.value && props.value.trim().toLowerCase() || ''; 
     var inputLength = inputValue.length; 

     var suggestions = states().filter(function (state) { 
      return state.name.toLowerCase().slice(0, inputLength) === inputValue; 
     }); 

     return React.createElement(Autosuggest, { 
      ref: props.ref, 
      suggestions: suggestions, 
      shouldRenderSuggestions: function shouldRenderSuggestions(value) { 
      return value && value.trim().length > 0; 
      }, 
      getSuggestionValue: function getSuggestionValue(suggestion) { 
      return suggestion.name; 
      }, 
      renderSuggestion: function renderSuggestion(suggestion) { 
      return React.createElement(
       'span', 
       null, 
       suggestion.name 
      ); 
      }, 
      inputProps: _extends({}, props, { onChange: handleOnChange }), 
      onSuggestionSelected: function onSuggestionSelected(e, _ref3) { 
      var suggestion = _ref3.suggestion; 

      addTag(suggestion.name); 
      }, 
      onSuggestionsClearRequested: function onSuggestionsClearRequested() {}, 
      onSuggestionsFetchRequested: function onSuggestionsFetchRequested() {} 
     }); 
     } 

     return React.createElement(TagsInput, { renderInput: autocompleteRenderInput, value: this.state.tags, onChange: this.handleChange }); 
    } 
    }]); 

    return AutocompleteExample; 
}(React.Component); 
+0

Autosuggest가 반환하는 소품을 보관하지 마십시오. 나는 그들이 어디에서 나오는 지 알지 못한다. –

0

React 구성 요소를 ES5로 직접 번역 할 수 없습니다. ES6가 React.createClass과 같은 다른 구문을 가진 자체 구문을 갖기 전에 반응하십시오.

ES6 class 구문을 사용하기 때문에기만적인 반응을 보이지만 React는 고유 한 방식으로 작업을 수행합니다. 모든 마법은 extends Component 안에 있습니다. 당신이 혼동하고있는 모든 것은 아마 .jsx이고 무엇이 render 인 지 (그것은 React 일입니다).

Babel transpiles 구성 요소를 사용자가 쓰지 않는 뭔가로 만들 수 있습니다. 어느 것이 당신이 찾고있는 것이 아닌지 (나는 생각한다). 클래스 구문이 혼란 스럽다면. 독립적으로 배우고, React의 맥락에서 ES6를 다루십시오.