gpt4 book ai didi

javascript - React 上下文 - 'contextType' 未定义

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:36 24 4
gpt4 key购买 nike

我正在使用应该支持 react Context 的 react-dom@16.6.1 和 react@16.6.1 并尝试运行一个与 react-context 相同的简单示例:

应用程序.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>

)
}
}

以及我想使用 Context 的 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>

)
}
}

如果我运行该应用程序,我会在 SearchBar.js 中得到 Line 44: 'contextType' is not defined no-undef 如果我删除此行,我会得到 {}我记录了 this.context

最佳答案

您没有正确使用上下文,因为您需要将其定义为类的静态属性并将其作为命名导入导入,因为您已将其导出为命名导入

import { ThemeContext } from '../App';

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

};

static contextType = ThemeContext;
componentDidMount(){
console.log(this.context); //{}
}

render() {

console.log(this.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>

)
}
}

关于javascript - React 上下文 - 'contextType' 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53924140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com