2016-08-17 10 views
-1

コンポーネントの子 "this"の値と親コンポーネントにはどうすれば到達できますか?コンポーネントの子「this」の値と親コンポーネントにはどうすれば到達できますか?

例:このように

class AComponent extends Component{ 
static getThis(){ 
    return this; 
    } 
} 




class MainComp extends Component{ 

componentDidMoud(){ 
    console.log(AComponent.getThis()); 
} 
} 

、どのように私はそれを得るのですか?

答えて

0

子コンポーネントから親コンポーネントを取得しないでください。何かを行う必要がある(親コンポーネントの状態に影響を与える)必要がある場合は、親から子へ関数を渡すための小道具として関数を渡します。あなたが何かを読む必要がある場合は、それを読むための小道具として親から子に関連するデータを渡します。

+0

、それがどのように行うことができますか? –

+0

何ができますか?私は、https://facebook.github.io/react/docs/thinking-in-react.htmlを通して、小道を通して関数とデータの両方を渡すことを実演することをお勧めします – John

0

子コンポーネントに使用する単純なプリミティブ値でも、親コンポーネントの状態を変更するために子コンポーネントによって使用できる関数でも、小道具を子に渡すことができます。ここに簡単な例があります。

ParentComponent.js

import React, { Component } from 'react'; 
import ChildComponent from './ChildComponent'; 

class ParentComponent extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     someState: true 
    }; 

    this.someFunction = this.someFunction.bind(this); 
    } 

    someFunction() { 
    this.setState({ 
     someState: false 
    }); 
    } 

    render() { 
    return (
     <ChildComponent aFunc={this.someFunction} aString="someValue"/> 
    ); 
    } 
} 

ChildComponent.js

import React, { Component } from 'react'; 

class ChildComponent extends Component { 
    constructor(props) { 
    super(props); 
    } 

    render() { 
    return (
     <div className={this.props.aString}> 
     <button onClick={this.props.aFunc}> 
      Some text 
     </button> 
     </div> 
    ); 
    } 
} 
関連する問題