繁体   English   中英

访问React类组件的返回变量

[英]Accessing return variable of React class component

我有反应成分,它返回一个整数。 类组件的结构如下:

class MyClass extends Component {
   constructor(props) {
        super(props);
        this.state = {
            variable : 0
        }
    }
    componentDidMount(){
       // do some works
       this.setSate({variable:$someValue});
    }
    render(){
        var temp = this.state.variable;
        return temp;
    }
}

我需要在渲染中的React的另一个类组件中获取MyClass返回的值。 如果我打来

render () {
  return (
    <div>{Myclass}</div>
  );
}

它工作正常。 有什么方法可以调用此外部返回,并将值分配给变量?

尝试改用“ this.props”。 你可以这样传递

   class MyClass extends Component {
   constructor(props) {
        super(props);
        this.state = {
            variable : 0
        }
    }
    componentDidMount(){
       // do some works
       this.setSate({variable:$someValue});
    }
    render(){
        const {variable} = this.state
        return (
             <MyOtherClass variable = {variable}/>
         );
    }
}

在MyOtherClass中:

render() {
    const {variable} = this.props
    return (
        <div>{variable}</div>
    );
}

您应该能够扩展MyClass并调用super.render()

class MyOtherClass extends MyClass {

    render() {
        const value = super.render();
        return (
            <div>{value}</div>
        );
    }
}

编辑codeandbox.io中的工作示例

暂无
暂无

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

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