2016-10-30 13 views
1

중복으로 표시하기 전에 질문을 완전히 읽으십시오.클래스를 확장하여 하위 구성 요소의 부모 구성 요소 상태를 변경하십시오.

두 구성 요소가 있습니다 (예 : AB). AReact.Component이고, BA입니다. 을 , B이라고하면 이 A 인 모든 항목을 B으로 사용할 수 있습니다.

제가 직면 한 문제는 A 상태를 업데이트하는 방법입니다. 이 방법은 B에서 호출합니다. 그래도 B이 아닌 A 상태가 업데이트됩니다. 이게 기대 되나요? 아니면 제가 잘못한 것입니다.

실시 예의

class A extends React.Component{ 
 
    constructor(props) { 
 
    super(props) 
 
    this.updatedState = this.updatedState.bind(this) //bound to this parent 
 
    this.state = { 
 
     text: 'Hello from the other side!' 
 
    } 
 
    } 
 
    
 
    updatedState(){ 
 
    this.setState({ 
 
     text: 'I must have called a thousand times!' 
 
    }) 
 
    } 
 
    
 
    render(){ 
 
    return <h1>{this.state.text}</h1> 
 
    } 
 
} 
 

 
class B extends A{ 
 
    constructor(){ 
 
    super() 
 
    } 
 
    
 
    render(){ 
 
    return <div> 
 
     <h1>{this.state.text}</h1> 
 
     <button onClick={this.updatedState}>Update state</button> 
 
    </div> 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <div> 
 
    <A/> 
 
    <B/> 
 
    </div>, 
 
    document.getElementById('app') 
 
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

다른 예

이것은 constructor 또는 super를 사용하지 않는다. 을 사용하여 new을 인스턴스화하고 메소드를 호출합니다. 메서드가 호출되었지만 렌더링이 트리거되지 않습니다. 이에 가정으로

class A extends React.Component{ 
 
    constructor(props) { 
 
    super(props) 
 
    this.updatedState = this.updatedState.bind(this) //bound to this parent 
 
    this.state = { 
 
     text: 'Hello from the other side!' 
 
    } 
 
    } 
 
    
 
    updatedState(){ 
 
    console.log('called') 
 
    this.setState({ 
 
     text: 'I must have called a thousand times!' 
 
    }) 
 
    } 
 
    
 
    render(){ 
 
    return <h1>{this.state.text}</h1> 
 
    } 
 
} 
 

 
class B extends A{ 
 
    render(){ 
 
    var parent = new A() 
 
    return <div> 
 
     <h1>{this.state.text}</h1> 
 
     <button onClick={parent.updatedState}>Update state</button> 
 
    </div> 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <div> 
 
    <A/> 
 
    <B/> 
 
    </div>, 
 
    document.getElementById('app') 
 
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

+0

@AndrewLi 나는 그것을 이해합니다! 'super'가 부모 클래스의'constructor'을 수행하고 부모 생성자 내부의 모든 것이 확장 클래스의 새로운 복사본으로 생성되기 때문입니다. 그거야? –

+0

* 확장 클래스 *에 대한 새로운 복사본으로 생성 된 것은 무엇을 의미합니까? – Li357

답변

0

두 번째 예는 작동하지 않습니다.

class B extends A{ 
    render(){ 
    var parent = new A() 
    return <div> 
     <h1>{this.state.text}</h1> 
     <button onClick={parent.updatedState}>Update state</button> 
    </div> 
    } 
} 

은 상기에서 참조 B의 인스턴스를 메모리에 0x001 ADRESS한다고 가정 A.에게

연장되는 객체 B가있다.

var parent = new A()는 A 객체를 만들고 메모리에있는 다른 주소, 예를 들어 0x002를 참조합니다. 이 참조는 객체 B의 인스턴스를 위해 예약 된 메모리에 보관됩니다. 그들은 단지 Has - realationship을가집니다. 그러나 B는 A를 확장 (B는 A)하므로 관계가 있습니다. A의

http://www.w3resource.com/java-tutorial/inheritance-composition-relationship.php

+0

감사합니다. 그러나 이것은 답변이 아니라 의견이 아닌가? –

+0

그리고 렌더가 될 인스턴스가 무엇이든간에 호출되지 않습니다. 두 번째 예제는 updatestate를 호출 할 때까지 작동합니다. –

+0

생성자를 추가하고 첫 번째 예인 수퍼 –

0

확장 B는 또한 A. 새로운 인스턴스와 B의 새로운 인스턴스를 연결하는 대신 유전 조성물을 시도하지 않는다. 구성에서 다루지 않는 상속의 특별한 사용 사례는 없습니다. 작문은 자연스럽고, 추론하기가 더 쉽고, 행동이보다 명확하고 훨씬 안전합니다.

작성 방법은 다음과 같습니다. 나는 정확하게 당신의 유스 케이스가 무엇인지 모르겠다. 그래서 다음의 리팩토링 된 예제가 당신이 성취하고자하는 것에 적합하지 않다면 나를 용서해라. 그럼에도 불구하고 상속을 사용하지 않고도 동일한 구성을 달성 할 수 있어야합니다.여기

class A extends React.Component { 
 
    render() { 
 
    return <h1>{this.props.displayText}</h1> 
 
    } 
 
} 
 

 
class B extends React.Component { 
 
    state = { 
 
    displayText: 'Hello from the other side!' 
 
    } 
 
    
 
    updateState() { 
 
    let displayText = 'I must have called a thousand times!'; 
 
    this.setState({ 
 
     displayText: displayText 
 
    },() => this.props.onUpdateClick(displayText)); 
 
    } 
 
    
 
    render() { 
 
    return <div> 
 
     <h1>{this.state.displayText}</h1> 
 
     <button onClick={this.updateState.bind(this)}>Update state</button> 
 
    </div> 
 
    } 
 
} 
 

 
class C extends React.Component { 
 
    state = { 
 
    displayTextA: 'Hello from the other side!' 
 
    } 
 
    
 
    changeA (value) { 
 
    this.setState({ 
 
     displayTextA: value 
 
    }); 
 
    } 
 
    
 
    render() { 
 
    return (
 
     <div> 
 
     <A displayText={this.state.displayTextA} /> 
 
     <B onUpdateClick={this.changeA.bind(this)} /> 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <div> 
 
    <C/> 
 
    </div>, 
 
    document.getElementById('app') 
 
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="app"></div>

당신이 도움이 될 수있는 몇 가지 게시물입니다 : -

+0

그러나 이것을 달성하기 위해 또 다른 구성 요소'C'를 작성해야합니다. 나는 '작곡'이 어떻게 작동 하는지를 안다. 우리가'class'와'extends'라는 단어를 사용하기 때문에 다른 방법이 있다면 나는 단지 궁금합니다. –

+0

[Stateless functional components] (https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#stateless-functional-components)를 확인할 수 있습니다. React의 클래스는 React의 라이프 사이클 메소드를 상속하거나 확장하기위한 간단하고 친숙한 구문을 제공하지만 OOP가 제공하겠다고 약속 한 모든 이점은 더 이상 사실이 아닙니다. [Goodbye, Object Oriented Programming] (https://medium.com/@cscalfani/goodbye-object-oriented-programming-a59cda4c0e53#.vrxey5sc9)을 참조하십시오. –

+0

상태 비 저장 구성 요소는 상태를 가질 수없는 순수 구성 요소이며 React의 라이프 사이클 메소드는 작동하지 않습니다. 진실은 React를 쓰는 동안 클래스를 정의하지 않는다는 것입니다. 그것은 ES6 구문으로 React를 작성하는 설탕 코팅 방식입니다. –

관련 문제