Reactjs 将属性传递给另一个组件-React
我需要将“notecards”(一个数组)从“Notecard.js”传递到“LoadQuestions.js”。控制台日志显示它正在传递,但当我在“return”中使用{notecards}时,它会将错误显示为“undefined”。你能看一下吗Reactjs 将属性传递给另一个组件-React,reactjs,Reactjs,我需要将“notecards”(一个数组)从“Notecard.js”传递到“LoadQuestions.js”。控制台日志显示它正在传递,但当我在“return”中使用{notecards}时,它会将错误显示为“undefined”。你能看一下吗 Notecard.js (without the imports): const useStyles = makeStyles((theme) => ({ root: { maxWidth: 345, }, media:
Notecard.js (without the imports):
const useStyles = makeStyles((theme) => ({
root: {
maxWidth: 345,
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
}));
export default function Notecard( {notecards} ) {
const classes = useStyles();
const next = () => {
console.log('Next Button Clicked')
};
const previous = () => {
console.log('Back Button Clicked')
};
const hint = () => {
console.log('Hint Button Clicked')
};
console.log({notecards});
return (
<Card className={classes.root}>
<div id="cardBody">
<CardHeader
title="Kate Trivia"
// subheader="Hint: In the 20th century"
/>
<CardContent>
<LoadQuestions notecards={notecards}/>
</CardContent>
</div>
</Card>
);
}
Notecard.js(不含导入):
const useStyles=makeStyles((主题)=>({
根目录:{
最大宽度:345,
},
媒体:{
高度:0,,
paddingTop:'56.25%',//16:9
},
}));
导出默认函数Notecard({notecards}){
const classes=useStyles();
常量下一个=()=>{
console.log('单击下一步按钮')
};
const previous=()=>{
console.log('单击后退按钮')
};
常量提示=()=>{
console.log('单击提示按钮')
};
console.log({notecards});
返回(
);
}
LoadQuestions.js(不带导入)
const{useState}=React;
导出默认函数LoadQuestions({notecards}){
const[currentIndex,setCounter]=useState(0);
console.log({notecards});
返回(
(
{on?
{props.notecards}您好:
{this.props[currentIndex].backSide}
}
)}
/>
{
console.log({notecards})
if(当前索引<(本道具长度-1)){
设置计数器(currentIndex+1);
}否则{
警报('不再有卡')
}
}}>下一张牌
{
如果(当前索引>0){
设置计数器(当前索引-1);
}否则{
警报('没有以前的卡')
}
}}>上一张牌
);
}
提前谢谢
这就是我为您提供的所有详细信息,但stack overflow确实希望我在提交之前添加更多内容。对不起 您应该检查道具是否存在,当它第一次呈现组件时,它没有道具,因此显示未定义 首先,我必须说,你已经解构了
notecards
out,所以不需要使用道具
如果你想使用道具,你应该改变
({notecards})
到(道具)
如果没有,您可以直接使用记事卡
,因为它已被分解
我给你两个建议
添加问号以检查是否存在
<h1>{props?.notecards} hi</h1>//in the case you want to use props
{props?.notecards}您好//如果您想使用props
或
在if语句中添加道具
<h1>{props.notecards?props.notecards:''} hi</h1> // if notecards is destructured remove the "props."
{props.notecards?props.notecards:'}嗨//如果notecards被解构,请删除“props”
谢谢!当我添加问号时,它说“props未定义”-但当我放置“props={notecards}”时,我认为我正在定义它?我更新了答案,在这一行LoadQuestions({notecards})
您正在分解notecards,以便您可以直接在组件上访问它,这样您可以说{notecards?notecards:'}您好
或者如果您想使用道具,您应该将第一行更改为加载问题(道具)
明白了!!非常感谢你!!
<h1>{props.notecards?props.notecards:''} hi</h1> // if notecards is destructured remove the "props."