[英]How to access state of another component
I have home component with header component how may I access the header states in home component here is the example 我有带有标头组件的home组件,如何在home组件中访问标头状态,这是示例
Header.JS Header.JS
class Header extends React.Component {
constructor(props){
super(props);
this.state = {
pageNumber: 1
}
}
render() {
return (
<div className="shopping-list">
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
</ul>
</div>
);
}
}
Home.js Home.js
import React, {Component} from 'react';
import Header from './header';
class App extends Component {
render() {
return (
<div>
<Header /> // I need to use the states of Header in this component
</div>
)
}
}
export default App;
I need to use the states of Header in Home component, is that possible? 我需要在Home组件中使用Header的状态,这可能吗?
Does this way is good for performance? 这样对性能有好处吗? Thank you
谢谢
You need to use state lifting
. 您需要使用
state lifting
。
Define a method eg liftTheState
in Header
component which will lift the state of Header
component by calling Home
component method with required data. 定义一个方法例如
liftTheState
在Header
部件,其将解除的状态Header
通过调用组件Home
与所需的数据组件的方法。
class Header extends React.Component {
constructor(props){
super(props);
this.state = {
pageNumber: 1
}
}
liftTheState=()=>{
this.props.callHomeMethod(this.state.pageNumber);
}
render() {
//...
}
}
In Home : 在家 :
Define a method eg callHomeMethod
in Home
component which will hold the Header
component data and passed the method as a prop to Header
component 在
Home
组件中定义一个方法,例如callHomeMethod
,它将保存Header
组件数据并将该方法作为prop传递给Header
组件
class App extends Component {
callHomeMethod = (someDataFromHeader)=>{
}
render() {
return (
<div>
<Header callHomeMethod = {this.callHomeMethod}/> // pass Home method here used for state lifting.
</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.