2017-11-21 15 views
0

別のクラスの状態を変更しREACTJSは:私は2つのファイルReactjs <br> file1.jsを持って

class App extends Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     data: [], 
     selection: null 
    }; 

file2.js

class SearchBar extends Component { 
InputChange =() => { 
    console.log(App.state); 
}} 

私が使用してクラスを使用するときに、クラスのアプリケーションの状態を変更したいですSearchBar、file2をfile1にインポートしました。ありがとうございました!私の英語は良くありません。

+0

ファイル1とファイル2はどのような関係も共有しています。シップ、 –

+2

リークガイドを読むことをお勧めします。 https://reactjs.org/docs/lifting-state-up.html – Kunukn

答えて

3

これは簡単です:Dあなただけそうのような状態を変更する関数に渡す必要があります。

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     data: [], 
     selection: null 
    }; 

    changeStuff(paramsIfAny) { 
    this.setState(/* whatever you want */); 
    } 

    render() { 
    ..... 
    <SearchBar changeHandler={this.changeStuff.bind(this)} /> 
    ..... 
    } 
} 

そしてあなたの検索バーのコンポーネントに

class SearchBar extends Component { 
InputChange = (params) => { 
    this.props.changeHandler(params); 
}} 

これは本当にコードに短縮されました私が言ったことを単純化する。私はあなたがそれがどのように行われることを願っています!

関連する問題