我正在尝试将状态从表单输入传递到最近的父组件,然后返回到我的应用程序中的另一个子组件。我想要将状态提升到的父组件是一个函数,将“闪存卡”作为一种非结构化的支柱,这对于我的应用程序的功能至关重要。我试图将状态提升到这个组件,在研究如何实现这个过程时,我注意到您提升状态的父组件必须是一个"Class‘组件’扩展React.Component“,当我这样做时,我不能使用‘闪存卡’作为一个去结构化的支柱,因为我得到了错误"Uncaught : Class扩展未定义的值不是构造函数,或者是Module.options.factory上的null ../src/FlashcarList.js (FlashcardList.js:6:1)”(响应刷新:6:1)“如何更改FLashcardList”组件,以便它可以接受闪存卡、道具以及构造函数中的绑定。以下是我将FlashcardList.js文件更改为类扩展表单后的样子:
import React from 'react'
import Flashcard from './Flashcard'
import NameForm from './NameForm'
import flashcards from './App'
export default class FLashcardList extends React.Component ({ flashcards }) {
// taking in the flashcards as destructured props so we dont have to make a props. variable
constructor(props) {
super(props);
this.state = {username: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange = (event) => {
this.setState({username: event.target.value});
}
render() {
return (
<div>
<NameForm onChoose={this.handleChange} />
<div className='card-grid'>
{flashcards.map(flashcard => { // loops through the flashcards api and maps each one to flashcard
return <Flashcard flashcard={flashcard} key={flashcard.id} choice={this.state.username} /> // each flashcard is then passed down to the "Flashcard.js" component we created returned w a unique id
})}
</div>
</div>
)
}
}
这是我改变它之前的样子:
import React from 'react'
import Flashcard from './Flashcard'
export default function FLashcardList({ flashcards }) {
// taking in the flashcards as destructured props so we dont have to make a props. variable
return (
// card-grid is a container so we can put all the cards in a grid to ensure they change in size proportionally to the size of the window //
<div className='card-grid'>
{flashcards.map(flashcard => { // loops through the flashcards api and maps each one to flashcard
return <Flashcard flashcard={flashcard} key={flashcard.id} /> // each flashcard is then passed down to the "Flashcard.js" component we created returned w a unique id
})}
</div>
)
}
发布于 2022-05-19 11:11:52
React.Component是类,而不是函数。你必须把它定义为:
export default class FLashcardList extends React.Component {
....
}
如果您想从道具中呈现闪存卡,您可以这样做:
render() {
return this.props.flashcards.map( // .... )
}
https://stackoverflow.com/questions/72309727
复制