我有一个反应应用程序,我正在尝试使用 JavaScript 文件中的数据构建一个导航栏组件。
我的 NavbarData.js 文件如下所示:
const NavbarData = [
{
id: 1,
text: "Typography"
},
{
id: 2,
text: "Buttons"
},
{
id: 3,
text: "icons"
}
]
export default NavbarData
我在用着.map()
迭代此数据并创建NavbarItem
我的 App.js 文件中的组件。
// Build navmenu items
const navbarItems = this.state.navbarData.map(function(item){
return <NavbarItem key={item.id} text={item.text} id={item.id}></NavbarItem>
});
这是我的 NavbarItem.js 文件
从 'react' 导入 React, { Component };
class NavbarItem extends Component{
render(){
return(
<>
<li key={this.props.id} id={this.props.id}>{this.props.text}</li>
</>
)
}
}
export default NavbarItem
所有这些给了我看起来像这样的东西。这太棒了。
但我想为每个添加一个点击侦听器。由于这是一个单页应用程序,我想渲染版式、按钮或图标组件。为此,我需要一个函数来更新父组件的状态,在我的例子中,父组件只是 App.js
所以我将以下函数放入 App.js 中
//This function changes the state so that different components can render
navClick(id) {
console.log('changed', id);
}
我确保将它绑定到 App.js 的构造函数中
this.navClick = this.navClick.bind(this);
我的整个 App.js 文件现在看起来像这样
//React stuff
import React, { Component } from 'react';
//Bootstrap stuff
import { Container, Row, Col } from 'reactstrap';
//Layout
import NavbarItem from './layout/NavbarItem'
import NavbarData from './layout/NavbarData'
//Components
import Typography from './components/Typography/Typography'
import Buttons from './components/Buttons/Buttons'
//Styles
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
constructor(){
super();
// State determines what component is active and loads navbar data
this.state = {
navbarData: NavbarData,
typography: true,
buttons: false,
icons: false
}
this.navClick = this.navClick.bind(this);
}
//This function changes the state so that different components can render
navClick(id) {
console.log('changed', id);
}
render() {
// Build navmenu items
const navbarItems = this.state.navbarData.map(function(item){
return <NavbarItem key={item.id} text={item.text} id={item.id}></NavbarItem>
});
// Determine what component to display in main area using state
let elementToDisplay;
if(this.state.typography){
elementToDisplay = <Typography></Typography>
}
else if(this.state.buttons){
elementToDisplay = <Buttons></Buttons>
}
////////////////////////////////////////////////////
return (
<Container fluid={true}>
<Row>
<Col>Header</Col>
</Row>
<Row>
<Col xs="12" sm="12" md="1" lg="1" xl="1">
<ul>
{navbarItems}
</ul>
</Col>
<Col xs="12" sm="12" md="11" lg="11" xl="11">
{elementToDisplay}
</Col>
</Row>
<Row>
<Col>Footer</Col>
</Row>
</Container>
);
}
}
export default App;
当我尝试像这样将 navClick 函数附加到映射的 NavbarItem 时,问题就出现了。
// Build navmenu items
const navbarItems = this.state.navbarData.map(function(item){
return <NavbarItem navigationWhenClicked={this.navClick} key={item.id} text={item.text} id={item.id}></NavbarItem>
});
我收到的错误如下:
类型错误:这是未定义的
当谷歌搜索这个问题时,这是最上面的帖子。React:“this”在组件函数中未定义 https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function
但这不是我的问题,因为我确保绑定我的函数。
我真的不知道我在这里做错了什么。任何帮助,将不胜感激。