簡體   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