중복으로 표시하기 전에 질문을 완전히 읽으십시오.클래스를 확장하여 하위 구성 요소의 부모 구성 요소 상태를 변경하십시오.
두 구성 요소가 있습니다 (예 : A
및 B
). A
은 React.Component
이고, B
은 A
입니다. 을 , 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>
은 물론이 예상된다. ''은''과 아무 관련이 없습니다. 그것들은 완전히 별개의 구성 요소 인스턴스입니다. – Li357
@AndrewLi 나는 그것을 이해합니다! 'super'가 부모 클래스의'constructor'을 수행하고 부모 생성자 내부의 모든 것이 확장 클래스의 새로운 복사본으로 생성되기 때문입니다. 그거야? –
* 확장 클래스 *에 대한 새로운 복사본으로 생성 된 것은 무엇을 의미합니까? – Li357