简体   繁体   中英

Accessing return variable of React class component

I have react component which returns an integer. Structure of the class component is as follows:

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

I need to fetch the value returned from MyClass in another class component in React within render. If I call like,

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

it works fine. is there any way to call this outside return, and assign the value to a variable?

Try utilizing 'this.props' instead. You can pass in something like this

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

And in MyOtherClass:

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

You should be able to extend MyClass and call super.render()

class MyOtherClass extends MyClass {

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

edit : working example in codesandbox.io

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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