그래서 많은 구성 요소를 확장하는 BaseComponent.jsx
이 있습니다. 이것은 잘 작동합니다.React : 상위 구성 요소에서 기본 클래스에 액세스하는 방법
class BaseComponent extends React.Component {
constructor(props){
super(props)
this.something = true
}
}
class OtherComponent extends BaseComponent {
constructor(props){
super(props)
console.log(this.something) // true
}
}
는하지만 지금은 더 높은 순서 구성 요소에서 구성 요소를 래핑하고 클래스를 장식 react-router
에서 withRouter(component)
를 사용해야합니다.
class OtherComponent extends BaseComponent {
constructor(props){
super(props)
console.log(this.something) // undefined
}
}
export default withRouter(OtherComponent)
문제는 지금은 BaseComponent
에서 속성에 액세스 할 수없고 사람들은 undefined
를 반환한다는 것입니다.
어떻게하면 HoC를 만들 수 있으며 동시에 기본 클래스의 속성에 액세스 할 수 있습니까?
동일한 동작이 표시되지 않습니다. 나는 당신의 예를 기반으로 한 바이올린을 만들었고 정확하게 "true"를 기록합니다. HoC 's가 구성하고있는 구성 요소를 변경하지 않았으므로 설명대로 작동해야하며이 피들이 설명하는대로 추가해야합니다. https://jsfiddle.net/okpLvu3e/ – ryanjduffy
안녕하세요 @ RyanDuffy이 간단한 예제가 작동하지만 아이를 추가하기 시작할 때 등은 그렇지 않습니다. 이것을 확인하십시오 : https://github.com/reactjs/react-router/issues/3514 React.Component 확장은 권장하지 않습니다. – Pier
대신 구성 요소 구성으로 원하는 것을 얻을 수 있습니까? React 구성 요소를 개발할 때 하위 클래스 화는 권장되지 않습니다. – loganfsmyth