반응형
대응: 기존 컴포넌트에 소품 추가
기존 요소를 추가 소품으로 복제하는 방법을 찾고 있습니다.
참조용:
this.mainContent = <Hello message="Hello world!" />
저는 이런 걸 하려고 했는데
React.createElement(this.mainContent, Object.assign({},
this.mainContent.props, { anotherMessage: "nice to meet ya!" }));
효과가 없어요.
어떻게 하면 좋을까요?
요소를 복제하고 다음을 사용하여 추가 소품을 추가해야 합니다.
const ClonedElementWithMoreProps = React.cloneElement(
this.mainContent,
{ anotherMessage: "nice to meet ya!" }
);
// now render the new cloned element?
사용하기 싫으면React.cloneElement()
, 다음의 스니펫을 사용할 수 있습니다.
function AddExtraProps(Component, extraProps) {
return <Component.type {...Component.props} {...extraProps} />;
}
React.createElement()
는 문자열 또는 React 클래스 유형을 첫 번째 매개 변수로 사용하기 때문에 요소를 복제하려고 하면 작동하지 않습니다.
물론 다른 React 요소를 상세하게 복사하여 옵션으로 새로운 소품을 제공할 수 있는 것도 있습니다.
var foo = React.cloneElement(this.mainContent, {anotherMessage: "nice to meet ya!"});
될 거야.
언급URL : https://stackoverflow.com/questions/36750387/react-adding-props-to-an-existing-component
반응형
'programing' 카테고리의 다른 글
텍스트 입력에서 ng-change가 작동하지 않음 (0) | 2023.03.08 |
---|---|
angularjs 형식 재설정 오류 (0) | 2023.03.08 |
반응 제어 구성 요소와 제어되지 않는 구성 요소란 무엇입니까? (0) | 2023.03.08 |
jQuery에서 키 누르기 사이의 작업 지연 (0) | 2023.02.26 |
타이프스크립트:리액트에 이력 오브젝트의 타입 체크를 추가하는 방법 (0) | 2023.02.26 |