我需要能够将一个函数作为道具传递给我的“任务”组件(请参见下面的代码),但是由于我构造项目的方式而不能。关于如何将{taskItems}
更改为Tasks实例的任何技巧,以便我可以将道具从App.jsx
传递到Tasks.jsx
,而又不会破坏应用程序的其余部分?
// App.jsx
import React, {useState} from 'react';
import Header from './Header'
import Card from './Card'
import cardData from './cardData'
import Dates from './Dates'
import Tasks from './Tasks'
import Footer from './Footer'
const initialState = [
{
id: 8,
chore: 'wash dishes'
},
{
id: 9,
chore: 'do laundry'
},
{
id: 10,
chore: 'clean bathroom'
}
]
function App() {
const [taskList, setUpdatedTasks] = useState(initialState)
const cardComponents = cardData.map(card => {
return <Card key={card.id} name={card.name} />
})
const taskItems = taskList.map(item => {
console.log(item)
return <Tasks key={item.id} task={item.chore} />
})
const updateHandler = (thing) => {
}
return (
<div>
<Header />
<Dates />
<div className='card-container'>
{cardComponents}
</div>
{taskItems} // how would I change this to an instance of <Tasks/> ?
<div>
<Footer />
</div>
</div>
)
}
export default App;
答案 0 :(得分:1)
实际上,这个问题来自您的思维方式,ReactJS并不像您想象的那样,ReactJS项目中的每个组件都是一个函数,而忘记了OOP原理。实例在这里没有意义。您可以尽可能轻松地完成操作,将功能像道具一样传递给Tasks.jsx
组件:
~~~
function App() {
const [taskList, setUpdatedTasks] = useState(initialState)
const cardComponents = cardData.map(card => (
<Card key={card.id} name={card.name} />
));
const taskItems = taskList.map(item => (
<Tasks
key={item.id}
task={item.chore}
func={setUpdatedTasks} // <--- Here
/>
);
});
~~~
答案 1 :(得分:0)
好吧,TaskItem是应用程序内的另一个组件,它也应该以道具的形式接收要传递给它的函数,所以它将像这样
// App.jsx
import React, {useState} from 'react';
import Header from './Header'
import Card from './Card'
import cardData from './cardData'
import Dates from './Dates'
import Tasks from './Tasks'
import Footer from './Footer'
const initialState= [
{
id: 8,
chore: 'wash dishes'
},
{
id: 9,
chore: 'do laundry'
},
{
id: 10,
chore: 'clean bathroom'
}
]
function App() {
const [taskList, setUpdatedTasks] = useState(initialState)
const cardComponents = cardData.map(card => {
return <Card key = {card.id} name = {card.name}/>
})
const taskItems = ({updateHandler}) =>
taskList.map(item => {
console.log(item)
return <Tasks key={item.id} task ={item.chore} updateHandler={updateHandler}/>
})
const updateHandler = (thing) => {
}
return (
<div>
<Header/>
<Dates/>
<div className = 'card-container'>
{cardComponents}
</div>
{taskItems} **// how would I change this to an instance of <Tasks/> ?**
<div>
<Footer/>
</div>
</div>
)
}
export default App;