我让它从classone调用classtwo中的getValue,但有另一种方法吗?是否有更简单的方法从classtwo获取this.state.value?
我尝试将静态getValue作为静态但它总是给我一个错误。有人可以帮忙吗?
谢谢!
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;
}
}
答案 0 :(得分:4)
应该是这样的。
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>
)
}
}