2017-11-14 7 views
0

デバイスの向きが変化したときにドロワの幅を動的に変更したい。これは私のコードドロワの幅を動的に設定する関数内のアクセス状態

componentDidMountonLayout関数が呼び出されたとき、私はupdateWidthを呼び出す
updateWidth = (width) => { 
    this.setState({drawerWidth: width/2 }); 
    } 

です。

drawerNavigator宣言では、drawerWidth: this.state.drawerWidthと設定しました。ここで私はdrawerWidth: this.state.drawerWidthが定義されていないことを私に知らせるエラーを得る。どうすればこの問題を解決できますか?

編集: これはあなたの引き出しのコンポーネントはステートレスなコンポーネントであるコンポーネントのコードの概要

const { width } = Dimensions.get('window'); 

const AppDrawer = DrawerNavigator(
{ 
    Category: { 
    path: '/bla', 
    screen: bla, 
    }, 
}, 
{ 
    drawerWidth: this.state.drawerWidth , 
    contentComponent: test, 
    initialRouteName: 'tets', 
    contentOptions: { 
    activeTintColor: '#fd67d3', 
    }, 
} 
); 


const AppNavigator = StackNavigator({ 
... 
}) 


class RootContainer extends Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     drawerWidth: 30 
    } 
} 

    onLayout(e) { 
    const {width, height} = Dimensions.get('window') 
    this.updateWidth(width); 
    } 

    updateWidth = (width) => { 
    this.setState({drawerWidth: width/2 }); 
    } 

    componentDidMount() { 
    this.updateWidth(width); 
} 
+0

ステートレスコンポーネントを使用していますか?そして、あなたはあなたのコンポーネントのより多くのコードを提供することができますか? – TimH

+0

@TimHもっとコードを追加しました – user567

答えて

0

です。それをクラスベースのコンポーネントとして再作成し、その中に状態を持たせることができます。ステートレスコンポーネントは、渡された小道具だけを取得できますが、ステートは保存できません。

+0

私は反応が新しく、私が示したすべてのチュートリアルはこの方法で引き出しを作成していました。ステートフルにする方法を教えてください。 – user567

+0

@ user567 TimHが正解を投稿しました。あなたはそれを試す必要があります。彼の答えは、クラスコンポーネントを正しく作成し、状態を初期化する方法を示しています。 –

0

コンストラクタで状態を初期化し、ステートフルなコンポーネントを使用する必要があります。

class AppDrawer extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      drawerWidth: 0 //or any other number 
     } 
    } 
+0

いいえ、私はすでにこれを試して、これは動作していません – user567

+0

RootContainerコンポーネントでコンストラクタを作成しようとしましたか? – TimH

+0

はい、ここで私が試したコードを更新しました – user567

関連する問題