我只是想问如何从其他类访问 this.state.sampleString ..这是我的代码
class MainClass extends Component {
constructor(props){
super(props)
this.state = {
sampleString: 'Test String'
}
this.getValue = this.getValue.bind(this);
}
getValue(){
//console.log(this.state.sampleString);
return this.state.sampleString
}
}
=========
这是我的第二个类中的函数,用于从 MainClass 获取“this.state.sampleString”的值
function getValueFromMainClass() {
var stringFromClassHeader = () => {HeaderWithBg.getValue()}
console.log(stringFromClassHeader.sampleString);
}
为什么它返回“未定义”?
多谢。我是 React Native 的新手。
您可以发送this.state.sampleString
作为其他组件的支柱并在那里使用它。一个简单的例子如下:
class MainClass extends Component {
constructor(props){
super(props)
this.state = {
sampleString: 'Test String'
}
this.getValue = this.getValue.bind(this);
}
getValue(){
//console.log(this.state.sampleString);
return this.state.sampleString
}
render(){
return (
<ChildClass sampleString={this.state.sampleString}/>
)
}
}
class ChildClass extends Component {
somefunction() {
//console.log(this.props.sampleString);
return this.props.sampleString
}
render(){
return ...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)