React propTypes 컴포넌트 클래스?
제공된 소품이 (인스턴스가 아닌) 컴포넌트 클래스인지 확인하려면 어떻게 해야 합니까?
예.
export default class TimelineWithPicker extends React.PureComponent {
static propTypes = {
component: PropTypes.any, // <-- how can I validate that this is a component class (or stateless functional component)?
};
render() {
return (
<this.props.component {...this.props} start={this.state.start}/>
);
}
}
사용하시는 분PropTypes >= 15.7.0신참PropTypes.elementType이 풀 리퀘스트에 추가되어 2019년 2월 10일에 공개되었습니다.
이 프로펠러 유형은 모든 컴포넌트(네이티브컴포넌트, 스테이트리스컴포넌트, 스테이트풀컴포넌트, Forward Ref)를 지원합니다.React.forwardRef, 컨텍스트 프로바이더/프로바이더).
그리고 이러한 요소가 없을 때 경고를 보냅니다. 전달된 소품이 요소일 때도 경고를 보냅니다(PropTypes.element타입이 아닙니다.
마지막으로 다른 소품 유형처럼 사용할 수 있습니다.
const propTypes = {
component: PropTypes.elementType,
requiredComponent: PropTypes.elementType.isRequired,
};
편집: 코드 앤 박스에 React의 FancyButton 예시와 새로운 기능과 연동되는 커스텀 프롭 체크 기능을 추가했습니다.React.forwardRefapi를 선택합니다.그React.forwardRefapi는 다음과 같은 개체를 반환합니다.render기능.이 소품 유형을 확인하기 위해 다음과 같은 커스텀 소품 체커를 사용하고 있습니다.- Ivan Samovar가 이 요구를 인식해 주셔서 감사합니다.
FancyButton: function (props, propName, componentName) {
if(!props[propName] || typeof(props[propName].render) != 'function') {
return new Error(`${propName}.render must be a function!`);
}
}
를 사용하는 것이 좋습니다.사실... PropType.func는 스테이트리스 기능 컴포넌트와 클래스 컴포넌트 모두에서 동작합니다.
이게 효과가 있다는 걸 증명하기 위해 샌드박스를 만들었어요내가 처음에 너에게 잘못된 정보를 줬다는 걸 고려하면 이게 필요하다고 생각했어.정말 죄송합니다!
작업 샌드박스 예제!
링크에 장애가 발생했을 경우의 테스트 코드는 다음과 같습니다.
import React from 'react';
import { render } from 'react-dom';
import PropTypes from "prop-types";
class ClassComponent extends React.Component {
render() {
return <p>I'm a class component</p>
}
}
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
const FSComponent = () => (
<p>I'm a functional stateless component</p>
);
const Test = ({ ClassComponent, FSComponent, FancyButton }) => (
<div>
<ClassComponent />
<FSComponent />
<FancyButton />
</div>
);
Test.propTypes = {
ClassComponent: PropTypes.func.isRequired,
FSComponent: PropTypes.func.isRequired,
FancyButton: function (props, propName, componentName) {
if(!props[propName] || typeof(props[propName].render) != 'function') {
return new Error(`${propName}.render must be a function!`);
}
},
}
render(<Test
ClassComponent={ ClassComponent }
FSComponent={ FSComponent }
FancyButton={ FancyButton } />, document.getElementById('root'));
언급URL : https://stackoverflow.com/questions/45315918/react-proptypes-component-class
'programing' 카테고리의 다른 글
| Oracle에서 임시 테이블스페이스를 축소하는 방법 (0) | 2023.02.25 |
|---|---|
| 이동에서 json을 표시하지 않음: 필수 필드입니까? (0) | 2023.02.25 |
| 각 메뉴 항목에 대한 추가 필드 추가 (0) | 2023.02.25 |
| 어떻게 반응해서 아래로 스크롤합니까? (0) | 2023.02.25 |
| Redux Thunk와 Redux Saga의 차이점은 무엇입니까? (0) | 2023.02.25 |