试图学习React和Reactstrap并尝试让Modals工作 . 当我单击按钮时,它应该切换Modal,但是现在它给了我这个错误:元素类型无效:期望一个字符串(对于内置组件)或类/函数(对于复合组件)但得到:undefined . 检查'App'的渲染方法
无法弄清楚我做错了什么 . 有人可以帮我告诉我这里哪里出错吗?感谢您提供的任何帮助 .
如果可能的话,我想使用最新版本的React和Reactstrap .
这是Codepen上的链接:https://codepen.io/lieberscott/pen/ddYNVP
const { Button,
Container,
Modal,
ModalTitle,
ModalHeader,
ModalBody,
ModalFooter } = Reactstrap;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
showModal: false
}
this.toggleModal = this.toggleModal.bind(this);
}
toggleModal() {
console.log("hello");
this.setState({
showModal: !this.state.showModal
})
}
render() {
return (
<Container>
<Headline />
<Box />
<Button outline color="primary" onClick={this.toggleModal}>Click</Button>
<Modal isOpen={this.state.showModal} toggle={this.toggleModal} className="modal">
<ModalHeader>
<ModalTitle id="modalTitle">
Add a Recipe
</ModalTitle>
</ModalHeader>
<ModalBody>
Modal body
</ModalBody>
<ModalFooter>
Modal footer
</ModalFooter>
</Modal>
</Container>
);
}
}
class Headline extends React.Component {
render() {
return (
<div>
Recipes
</div>
);
}
}
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [
{
name: "Tofu tacos",
ingredients: [
"Shells",
"lettuce",
"tofu",
"paprika"
]
},
{
name: "Spaghetti",
ingredients: [
"pasta",
"sauce",
"salt"
]
}
] // end of items
} // end of this.state
} // end of constructor
render() {
const allitems = this.state.items.map(item => {
return (
<div>
{item.name}
</div>
);
})
return (
<div>
{allitems}
</div>
);
}
}
const app = document.getElementById("app");
ReactDOM.render(<App />, app);
1 回答
我不知道如何通过codepen分享我的代码,就像你一样,抱歉 .
我做了这些改变:
Button onClick事件,当你执行
onClik={this.something}
这个this
时会引用Button元素 . 我改为:我什么时候
onClick={ () => this.something() }
允许我利用我班上的方法 .只需查看console.log输出,您将看到单击按钮将showModal更改为
true
或false
.看一下cephalization的答案:https://forum.freecodecamp.org/t/difference-in-reactjs-onclick-function-binding/116027/2