作为新手React开发者,我想要做的就是在父组件中将一些常量传递给子组件。
在提供的代码片段中,您已在父组件App
中定义了一个常量PIinput
,并尝试将其传递给子组件Card
。但是,在子组件中访问props.label
和props.inputs
时遇到了未定义的问题。
以下是您提供的React JSX代码及其对应的描述翻译:
// 导入样式和组件
import './App.css';
import { Display } from './Display';
import { Card } from './Card';
// App组件导出函数
export function App() {
// 定义要传递给子组件的常量对象
const PIinput = {
label: '个人信息',
inputs: ['姓名', '地址', '邮箱', '电话'],
};
// 在 JSX 中返回元素,并将 PIinput 对象作为属性传递给 Card 组件
return (
<>
<div>
{/* 传递props={PIinput} */}
<Card props={PIinput} />
</div>
<Display />
</>
);
}
// Card组件导出函数
export function Card(props) {
// 尝试打印props对象和props.label属性
console.log(props, props.label);
// 返回一个带有props信息的卡片元素
return (
<div className='card'>
{/* 显示label属性值 */}
<h2>{props.label}</h2>
{/* 创建一个表单,遍历并显示inputs数组中的每一项 */}
<form>
{props.inputs.map((item) => {
return <h3>{item}</h3>;
})}
</form>
</div>
);
}
当我尝试将PIinput
传递给Card
组件,并在其中console.log(props)
时,它会显示出我的对象;但当我尝试通过console.log
或使用props.label
、props.inputs
时,却得到未定义的结果。
请问应如何正确地传递这些值呢?