
HTML5 사용자 정의 요소 API를 사용하여 HTML의 어휘를 확장하는 REACT 생태계의 모든 이점과 진정으로 재사용 할 수 있고 상호 운용 가능한 프레임 워크의 제외 구성 요소를 만듭니다.
npm install react-standalone --save 재사용 가능한 구성 요소를 구성하는 방법에 대한 아이디어에 대한 mars-weather 구성 요소를 살펴보십시오. 그러나 본질적으로 구성 요소는 mars-weather , 반응 component 및 osom 사용한 선택적 스키마와 같은 태그 이름으로 구성됩니다.
import { createModule } from 'standalone' ;
import schema from './schema' ;
import component from './component' ;
export default createModule ( 'mars-weather' , { schema , component } ) ; 패키지를 만들면 DOM에 포함될 수있는 제공된 tagName 으로 사용자 정의 요소가 생성됩니다. 요소가 DOM에서 제거 된 경우 componentWillUnmount 와 같은 모든 React 라이프 사이클 방법이 호출됩니다.
< mars-weather /> mars-weather 구성 요소는 완전히 사용자 정의 요소이므로 각 JavaScript 프레임 워크 (각도, vue, React, Cycle, Ember, Vanilla 등)에 포함시킬 수 있습니다.
보너스 : 진정한 중합체 같은 느낌을 위해 그림자 경계와 함께 Keo를 사용하십시오.
사용자 정의 요소에 속성을 지정하면 속성의 값이 소품으로 구성 요소로 전달됩니다. state 에 대한 모든 변경 사항은 구성 요소에 내부적으로 처리되는 반면, 요소의 속성에 대한 변경 사항은 업데이트 된 props 으로 재 렌더를 유발합니다.
mars-weather 예에서는 기본 소품을 반환하기 위해 getDefaultProps 메소드를 설정했지만 사용자는 data-unit 이라는 data 속성을 전달하여 unit Prop를 무시할 수 있습니다.
< mars-weather data-unit =" C " /> 위의 경우, data-unit 접두사가 모든 data- 접두사를 제거한 다음 구성 요소를 다시 렌더링하여 unit - Standalone 속성이 장치로 변환되어 속성에 액세스 할 수 있습니다 this.props.unit .
모든 HTML 속성이 string S이므로 Standalone 사용하면 구성 요소의 스키마를 지정할 수 있으므로 string 속성을 osom 사용하는 데이터 유형으로 변환합니다.
export default {
unit : {
type : String ,
default : 'F'
}
} ; 구성 요소에 사용할 스키마를 구성한 후에는 통과 할 데이터 유형을 지정하는 일반적인 React propTypes 행복하게 설정할 수 있습니다.
사용자 정의 이벤트를 사용하면 구성 요소와 외부 세계 간의 통신 채널을 쉽게 설정할 수 있습니다.
// Instantiate `CustomEvent` and then specify the name of the event, followed
// by the payload which will be passed to your listener function.
const event = new CustomEvent ( 'migrate-planets' , {
bubbles : true ,
detail : {
planet : 'Saturn'
}
} ) ;
findDOMNode ( this ) . dispatchEvent ( event ) ; 이벤트를 bubbles: true 그렇지 않으면 이벤트는 findDOMNode(this) .parentNode를 사용하여 mars-weather 노드에서 이벤트를 발송하지 않는 한 mars-weather 노드로 버블 링하는 대신 findDOMNode(this).parentNode ) 노드에서 단순히 중단됩니다.
구성 요소 내에서는 이벤트 ( CustomEvent )를 사용하여 dispatchEvent 사용한 다음 외부에서 addEventListener 사용하여 mars-weather 와 같은 사용자 정의 요소를 바인딩합니다.
const node = document . querySelector ( 'mars-weather' ) ;
node . addEventListener ( 'migrate-planets' , event => {
// Update the `data-planet` attribute to reflect the newly migrated planet
// which will cause the component to re-render with the update prop.
node . setAttribute ( 'data-planet' , event . detail . planet ) ;
} ) ; 구성 요소에서 setAttribute 호출하면 구성 요소를 다시 렌더링하기 위해 반응하므로, 특히 수많은 속성을 정의하는 경우 JSON 페이로드를 구성 요소에 제공하는 것이 유용 할 수 있습니다. 이것은 또한 많은 소품과 재 렌더를 업데이트하기 위해 하나의 setAttribute 만 필요하기 때문에 성능에 도움이됩니다.
스키마를 정의하면 JSON으로 구문 분석 할 속성을 지정할 수 있습니다.
export default {
payload : {
type : JSON . parse
}
} 요소의 data-payload 속성에 JSON 문자열을 첨부하면 JSON.parse 사용하여 객체에 구문 분석하고 PropTypes.shape 사용하여 propTypes 에서 정의 할 수있는 react 구성 this.props.payload 로 전달됩니다.
모든 Standalone 구성 요소는 HTMLElement.prototype 확장하고 요소에 사용자 정의 함수를 추가 할 수 있습니다.이 요소에 대한 참조가 있으면 호출 할 수 있습니다. mars-weather 의 방법을 살펴보십시오.
const getWeather = function ( ) {
const weather = this . component . state . weather . atmoOpacity . toLowerCase ( ) ;
return `The current weather on Mars is ${ weather } !` ;
} ;
// ...
document . querySelector ( 'mars-weather' ) . getWeather ( ) ; 구성 요소가 DOM에 추가되면 HTMLElement 프로토 타입을 업데이트하여 렌더링 된 구성 요소를 getPrototypeOf(this).component -이를 통해 편리하게 props 과 state 액세스하고 반응 구성 요소에 내부 기능을 호출 할 수 있습니다.
this.component 는 구성 요소가 DOM에 추가 된 후에 만 사용할 수 있습니다.
사용자 정의 요소 API를 사용하면 기존 요소를 확장 할 수 있습니다 - is 속성을 사용하여 전문화하십시오. Standalone 사용하면 확장 할 요소를 전달하여 요소를 확장 할 수 있습니다.
// Creates a `mars-weather` element.
export default createModule ( 'mars-weather' , { schema , methods , component } ) ;
// Creates a `input[is="mars-weather"]` element.
export default createModule ( 'input/mars-weather' , { schema , methods , component } ) ; 알려진 요소를 확장 할 때 요소가 프로토 타입을 확장 할 것입니다. mars-weather 요소 위의 경우 input 및 HTMLInputElement 프로토 타입을 확장합니다.
* 우수한 webcomponents-lite.js polyfill (13k gzipped)이 필요합니다.