programing

React 클래스 내에서 propTypes와 defaultProps를 정적 소품으로 넣어도 될까요?

cafebook 2023. 2. 22. 23:13
반응형

React 클래스 내에서 propTypes와 defaultProps를 정적 소품으로 넣어도 될까요?

지금까지 꽤 오랫동안 이렇게 해왔습니다.

export default class AttachmentCreator extends Component {
  render() {
    return <div>
      <RaisedButton primary label="Add Attachment" />
    </div>
  }
}

AttachmentCreator.propTypes = {
  id: PropTypes.string,
};

하지만 사람들이 이런 식으로 하는 걸 본 적이 있어요

export default class AttachmentCreator extends Component {
  static propTypes = {
    id: PropTypes.string,
  };

  render() {
    return <div>
      <RaisedButton primary label="Add Attachment" />
    </div>
  }
}

실제로 컨스트럭터 외부에서 초기 상태를 설정하는 사람도 있습니다.이게 좋은 방법인가요?자꾸 신경이 쓰이는데, 누군가가 디폴트 소품을 정적으로 설정하는 것은 좋은 생각이 아니라고 말한 것을 기억합니다.그냥 왜 그랬는지 기억이 나지 않습니다.

사실 성능 면에서도 똑같습니다.React.JS는 비교적 새로운 테크놀로지이기 때문에 어떤 것이 베스트 프랙티스로 간주되는지는 아직 명확하지 않습니다.누군가를 신뢰하고 싶다면 다음 AirBNB 스타일가이드를 확인하십시오.

https://github.com/airbnb/javascript/tree/master/react#ordering

import React, { PropTypes } from 'react';

const propTypes = {
  id: PropTypes.number.isRequired,
  url: PropTypes.string.isRequired,
  text: PropTypes.string,
};

const defaultProps = {
  text: 'Hello World',
};

class Link extends React.Component {
  static methodsAreOk() {
    return true;
  }

  render() {
    return <a href={this.props.url} data-id={this.props.id}>{this.props.text}</a>
  }
}

Link.propTypes = propTypes;
Link.defaultProps = defaultProps;

export default Link;

propTypes 객체 리터럴을 사용하여 const를 선언하고 클래스를 매우 깨끗하게 유지하고 나중에 정적 속성에 할당합니다.저는 개인적으로 이 접근법을 좋아합니다.

네, 바벨(또는 다른 트랜스필러)에게는 완전히 합법적입니다.

class DataLoader extends React.Component {
  static propTypes = {
    onFinishedLoading: PropTypes.func
  }

  static defaultProps = {
    onFinishedLoading: () => {}
  }
}

...어쨌든 이렇게 되니까요.

class DataLoader extends React.Component {}

DataLoader.propTypes = {
  onFinishedLoading: PropTypes.func
};

DataLoader.defaultProps = {
  onFinishedLoading: () => {}
};

정적 필드는 후드 아래 클래스 객체의 속성으로 변환됩니다.여기 Babel REP를 보세요.

또한 클래스 본문에 직접 상태 또는 기타 클래스 필드를 할당하면 생성자로 변환됩니다.

비함수 속성은 현재 es2015 클래스에 지원되지 않습니다.es2016에 대한 제안입니다.두 번째 방법이 훨씬 편리하지만 구문을 지원하려면 플러그인이 필요합니다(이러한 플러그인은 매우 일반적인 babel 플러그인입니다).

한편 오픈소스 프로젝트에서는 TypeScript 인터페이스 또는 ActionConstants와 같은 프로프타입을 취급하고 있으며 실제로 다양한 컴포넌트 프로펠러 타입을 수용한 개별 폴더/파일을 생성하여 컴포넌트로 Import합니다.

즉, 두 구문 모두 사용할 수 있지만 ES2015만 사용하는 경우 사양에서는 아직 후자의 구문이 지원되지 않습니다.

컴포넌트가 스테이트리스이며, 즉 자체 상태가 전혀 변경되지 않는 경우 스테이트리스 컴포넌트로 선언해야 합니다(export default function MyComponent(props) 선언을 합니다.propTypes★★★★★★★★★★★★★★★★★★.

초기 상태 선언을 컨스트럭터에 넣는 것이 좋은 프랙티스인지 아닌지는 당신에게 달려 있습니다.에서는 초기 를 로로 initial initial initial in in in 、 in in in in 。componentWillMount()가 '마음에 들지 않는다'는 이유로super(props)시공자와 함께 사용해야 하는 보일러 플레이트입니다.

언급URL : https://stackoverflow.com/questions/36778260/is-it-ok-to-put-proptypes-and-defaultprops-as-static-props-inside-react-class

반응형