programing

대응: 기존 컴포넌트에 소품 추가

lastcode 2023. 3. 8. 21:12
반응형

대응: 기존 컴포넌트에 소품 추가

기존 요소를 추가 소품으로 복제하는 방법을 찾고 있습니다.

참조용:

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

반응형