web-dev-qa-db-ja.com

React context-'contextType' is not defined

私は[email protected][email protected]を使用していて、react Contextをサポートし、 react-context と同じ簡単な例を実行しようとしています。

app.js

import React, { Component } from 'react';
import AppManger from './components/AppManger';
import './App.css';
export const ThemeContext = React.createContext({a1:'a1'});

class App extends Component {

  render() {

    return (

      <div className="App">
        <h1>Manage Storefront Services Products</h1>
        <ThemeContext.Provider value="dark">
          <AppManger />
        </ThemeContext.Provider>

      </div>

    );
  }
}

export default App;

AppManger.js(コンテキスト参照がありません)

import React, { Component } from 'react'
import SearchBar from './SearchBar';
export default class AppManger extends Component {


    constructor(props) {
        super(props);
        this.onSearchBarChange = this.onSearchBarChange.bind(this);
        this.state = {
            searchValue: '',
            errorLoading: false,
            errorObj: null,
        }
    }

    onSearchBarChange(e) {
        e.persist();
        this.setState({ searchValue: e.target.value });
    }

    render() {
        return (

            <div>
                <a href="/subsadmin/saml/logout">Log out</a>
                <SearchBar onSearchBarChange={this.onSearchBarChange} inAttrView={this.state.onAttrPage} />
            </div>

        )
    }
}

そして、コンテキストを使用したいSearchBar.js:

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


export default class SearchBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showModal: false,
      showAttrModal: false
    };

  };


  componentDidMount(){
    console.log(this.context); //{}
  }

  render() {
    const contextType = ThemeContext;
    console.log(contextType); //{}
    return (

      <div>
        {contextType} /*'contextType' is not defined  no-undef */
        <input type="text" style={searchBoxStyle} className="form-control" onChange={this.props.onSearchBarChange} placeholder="Search for..." id="sku" name="sku" />

      </div>

    )
  }
}

アプリを実行すると、Line 44: 'contextType' is not defined no-undef SearchBar.jsでこの行を削除すると、{}ロギングするときthis.context

5
Itsik Mauyhas

AppではなくThemeContextをインポートしました。

使用する import { ThemeContext } from '../App.js;

1
Max Kuzmenko

ここで問題:

componentDidMount() {
    console.log(this.context);
}

this.context変数が見つかりません。

static contextType = 

To

const contextType = 
0