我对React很陌生,正在尝试启动一个应用程序。在我的主要App.js文件中,我正在设置一些虚拟道具数据,以传递给子组件Schedule
。我试图使用箭头函数vs类或函数来创建组件。我确定我缺少一些非常基本的东西。我因缺少逗号而遇到了许多ESLint错误,并且“当前的Javascript版本不支持类型。”
App.js:
import React from 'react';
import PropTypes from 'prop-types';
import { render } from 'react-dom';
import Schedule from './components/home/SchedulePage';
const App = () => (
orders: [
{
id: 1,
title: 'First Order',
desc: 'This order is for .'
},
{
id: 2,
title: 'Second Order',
desc: 'This order is for .'
},
{
id: 3,
title: 'Third Order',
desc: 'This order is for .'
},
{
id: 4,
title: 'Fourth Order',
desc: 'This order is for .'
},
{
id: 5,
title: 'Fifth Order',
desc: 'This order is for .'
}
]
return (
<div>
<Schedule/>
</div>
);
);
export default App;
我也不确定如何将orders
发送到Schedule
。
答案 0 :(得分:1)
您可以像这样将orders
传递到Schedule
:
<Schedule orders={orders} />
您可以随便命名,假设您要命名此道具banana
,您可以这样做:
<Schedule banana={orders} />
然后您可以像这样在orders
组件中访问Schedule
:
const Schedule = (props) => {
console.log(props.orders)
}
这反映了您在第一部分中给它命名的名称,因此,再次,如果您将其命名为banana
,则可以按以下方式访问它:
const Schedule = (props) => {
console.log(props.banana)
}
答案 1 :(得分:1)
组件主体中的语法不正确。应该是
import PropTypes from 'prop-types';
import { render } from 'react-dom';
import Schedule from './components/home/SchedulePage';
const orders = [
{
id: 1,
title: 'First Order',
desc: 'This order is for .'
},
{
id: 2,
title: 'Second Order',
desc: 'This order is for .'
},
{
id: 3,
title: 'Third Order',
desc: 'This order is for .'
},
{
id: 4,
title: 'Fourth Order',
desc: 'This order is for .'
},
{
id: 5,
title: 'Fifth Order',
desc: 'This order is for .'
}
];
const App = () => {
return (
<div>
<Schedule orders={orders} />
</div>
);
};
export default App;
答案 2 :(得分:0)
您的标记:
<Schedule orders={orders} />
然后您可以通过orders
组件中的props.orders
访问Schedule
道具。
答案 3 :(得分:0)
这是将数据从父组件传递到子组件的方法
let orders = [
{
id: 1,
title: 'First Order',
desc: 'This order is for .'
},
{
id: 2,
title: 'Second Order',
desc: 'This order is for .'
},
{
id: 3,
title: 'Third Order',
desc: 'This order is for .'
},
{
id: 4,
title: 'Fourth Order',
desc: 'This order is for .'
},
{
id: 5,
title: 'Fifth Order',
desc: 'This order is for .'
}
]
const App = () => (
<div>
<Schedule orders={orders}/>
</div>
);
const Schedule=({orders})=>{
return <div>Schedule</div>
}
您可以迭代每个对象并将其传递给子组件
const App = () => (
<div>
{orders.map(order => (
<Schedule key={order.id} order={order}/>
))}
</div>
);
const Schedule = ({ order }) => {
return (
<div key={order.id}>
<p>
{order.title}, {order.desc}
</p>
</div>
);
};