繁体   English   中英

我如何从其他组件中获取this.state.value

[英]How do I get a this.state.value from other components in react native

我可以从classone的classtwo调用getValue来工作,但是还有另一种方法吗? 有没有更简单的方法从classtwo获取this.state.value?

我尝试将static getValue设置为static,但始终会引发错误。 有人可以帮忙吗?

谢谢!

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>
            )
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM