Javascript 如何从react native中的其他组件获取this.state.value
我从classone中调用Class2中的getValue,但还有其他方法吗?有没有更简单的方法从Class2获取this.state.value 我尝试将静态getValue设置为静态,但它总是给我一个错误。有人能帮忙吗 谢谢Javascript 如何从react native中的其他组件获取this.state.value,javascript,reactjs,ecmascript-6,react-native,Javascript,Reactjs,Ecmascript 6,React Native,我从classone中调用Class2中的getValue,但还有其他方法吗?有没有更简单的方法从Class2获取this.state.value 我尝试将静态getValue设置为静态,但它总是给我一个错误。有人能帮忙吗 谢谢 class ClassOne extends React.Component { constructor(props) { super(props); this.state = { classtwo:
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;
}
}
应该是这样的
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>
)
}
}
ClassOne类扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
第二类:0,
};
}
组件将接收道具(下一步){
if(nextProps.classtwo&&(this.state.classtwo!=nextProps.classtwo))
{this.setState({class2:nextrops.class2});}
}
}
类2扩展了React.Component{
建造师(道具){
超级(道具);
this.changeValue=this.changeValue.bind(this);
此.state={
数值:100,
};
}
更改值(值){
this.props.changeValue(this.state.value);
此.setState(值:value);
}
}
类ClassZero扩展了React.Component{
建造师(道具){
超级(道具);
this.changeValue=this.changeValue.bind(this);
此.state={
classTwoValue:0,
};
}
更改值(值){
this.setState(classTwoValue:value);
}
render(){
返回(
)
}
}
您所说的“宣布新的”是什么意思?这有什么不对吗?“我试着将static getValue设置为static”-为什么要这样做?在整个应用程序生命周期中,我只需要一个实例。就像我只有一个应用程序的搜索栏,我一直在为classthree classfour声明新的searchbar()。为什么您的多个类都包含一个搜索栏的实例?谁实例化了要在应用程序中使用的单个搜索栏
?也许它应该是构造函数的参数?顺便说一句,new
不是一个声明,它是一个构造。这看起来像是一种方法。为什么你认为会有另一种方法呢?谢谢janaka,但我不明白这一部分。你能解释一下吗:组件将接收道具(nextrops)
当组件收到道具时,在运行渲染之前,会触发此命令。请参见本机生命周期。。