如何从不同的类testState
访问状态变量UserAuthentication
?
我尝试了这个但没有成功:
import React from 'react';
import UserAuthenticationUI from './UserAuthentication/UserAuthenticationUI';
class App extends React.Component {
constructor(props) {
super(props);
this.userAuthenticationUI = React.createRef();
this.state={
testState: 'test message'
}
}
render() {
return(
<div>
<UserAuthenticationUI ref={this.userAuthenticationUI} />
<div>
)
}
}
export default App;
如何从this.state.teststate
类访问UserAuthenticationUI
?
import React from "react";
import App from '../App';
class UserAuthenticationUI extends React.Component {
constructor(props) {
super(props);
this.app = React.createRef();
}
render() {
return(
<div>
<App ref={this.app} />
{console.log(this.state.testState)}
</div>
)
}
}
export default UserAuthenticationUI;
答案 0 :(得分:0)
您应该换个思路。
尝试通过GET方法读取变量,并通过SET方法进行设置。 不要尝试立即调用变量
希望这会有所帮助。
答案 1 :(得分:0)
您需要通过道具传递它。
View viewHorizontleLine = new View(this); v.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
5 )); viewHorizontleLine.setBackgroundColor(Color.parseColor("#A1A1A1"));
LinearLay.addView(viewHorizontleLine);
UserAuthenticationUI:
import React from "react";
import UserAuthenticationUI from "./UserAuthentication/UserAuthenticationUI";
class App extends React.Component {
constructor(props) {
super(props);
this.userAuthenticationUI = React.createRef();
this.setParentState = this.setParentState.bind(this);
this.state = {
testState: "test message"
};
}
setParentState(newStateValue){ // this is called from the child component
this.setState({
testState: newStateValue
})
};
render() {
return (
<div>
<UserAuthenticationUI
stateVariable={this.state.testState}
ref={this.userAuthenticationUI}
setParentState={this.setParentState}
/>
</div>
);
}
}
export default App;
答案 2 :(得分:0)
您可以通过道具:
import React from 'react';
import UserAuthenticationUI from
'./UserAuthentication/UserAuthenticationUI';
class App extends React.Component {
constructor(props) {
super(props);
this.userAuthenticationUI = React.createRef();
this.state={
testState: 'test message'
}
}
render(){
return(
<div>
<UserAuthenticationUI testState={this.state.testState} />
<div>
)}
}
export default App;
UserAuthenticationUI:
import React from "react";
import App from '../App';
class UserAuthenticationUI extends React.Component
{
constructor(props){
super(props);
}
render(){
return(
<div>
<App/>
{console.log(this.props.testState)}
</div>
)}
}
export default UserAuthenticationUI;
答案 3 :(得分:0)
您可以通过道具访问它:
<div>
<UserAuthenticationUI testState={this.state.testState} ref={this.userAuthenticationUI} />
<div>
并在UserAuthenticationUI类中对其进行访问:
<div>
<App ref={this.app} />
{console.log(this.props.testState)}
</div>