javascript 我如何从 react native 中的其他组件获取 this.state.value
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32826277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get a this.state.value from other components in react native
提问by phongyewtong
I got it to work calling getValue in classtwo from classone but is there another way of doing this? Is there a easier way to get this.state.value from classtwo?
我让它在 classtwo 中从 classone 调用 getValue 工作,但是还有另一种方法吗?有没有更简单的方法从 classtwo 获取 this.state.value?
I tried putting static getValue as static but it always throw me an error. Anyone can help?
我尝试将静态 getValue 设置为静态,但它总是给我一个错误。任何人都可以帮忙吗?
Thanks!
谢谢!
class ClassOne extends React.Component {
constructor(props) {
super(props);
this.state = {
classtwo: new ClassTwo(),
};
}
CallGetValue(){
this.state.classtwo.getValue();
}
}
class ClassTwo extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 100,
};
}
getValue(){
return this.state.value;
}
}
回答by J. Mark Stevens
It should look like this.
它应该是这样的。
class ClassOne extends React.Component {
constructor(props) {
super(props);
this.state = {
classtwo: 0,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.classtwo && (this.state.classtwo != nextProps.classtwo))
{this.setState({classtwo: nextProps.classtwo});}
}
}
class ClassTwo extends React.Component {
constructor(props) {
super(props);
this.changeValue = this. changeValue.bind(this);
this.state = {
value: 100,
};
}
changeValue(value){
this.props.changeValue(this.state.value);
this.setState(value: value);
}
}
class ClassZero extends React.Component {
constructor(props) {
super(props);
this.changeValue = this. changeValue.bind(this);
this.state = {
classTwoValue: 0,
};
}
changeValue(value){
this.setState(classTwoValue: value);
}
render() {
return (
<div>
<ClassOne classtwo={this.state.classTwoValue}/>
<ClassTwo changeValue={this.changeValue}/>
</div>
)
}
}