[英]ReactJS: Props is undefined in child component and I can't pass props parameters throught parent
I'm learning React and I have a problem trying to read my props in a child component.我正在学习 React,但在尝试读取子组件中的道具时遇到问题。
The child component is:子组件是:
const HelloWorldApp = ( props ) => {
console.log(props);
return (<>
<h2> {props} </h2>
</>
);
}
export default HelloWorldApp;
The parent is:父母是:
import React from 'react';
import {createRoot} from 'react-dom/client';
import HelloWorldApp from './FirstApp';
import { SecondApp } from './SecondApp';
import './styles.css';
createRoot(document.getElementById('root')).render(HelloWorldApp());
createRoot(document.getElementById('raiz')).render(SecondApp());
1) What is the problem? 1)有什么问题? 2) How can I pass props from the parent to the children component? 2)如何将道具从父组件传递给子组件?
I think the problem is in the render function.我认为问题出在渲染 function 中。 You need something like this:你需要这样的东西:
createRoot(document.getElementById('root'))
.render(<HelloWorldApp />);
In react, you don't need to render all the components in separate CreateRoot..在反应中,您不需要在单独的 CreateRoot.. 中渲染所有组件。
render your child component with props inside the parent component使用父组件内的道具渲染您的子组件
The parent Component父组件
import React from 'react';
import {createRoot} from 'react-dom/client';
import HelloWorldApp from './FirstApp';
import './styles.css';
createRoot(document.getElementById('root')).render(<HelloWorldApp data="propsData" />);
The child Component子组件
const HelloWorldApp = ( props ) => {
console.log(props);
// {data: "dummyData"}
return (<>
// you can't able to render object inside the jsx
<h2> {props.data} </h2>
</>
);
}
export default HelloWorldApp;
The structure React program is on constantly changing over the time, whereby i recommend you use command npm create-react-app
to have the latest standards of programming in that framework. React 程序的结构会随着时间不断变化,因此我建议您使用命令npm create-react-app
在该框架中拥有最新的编程标准。 Only one createRoot
is necessary in React renderize DOM, and i recommend you receive parameters with destructuring in child component, the parameters must been passed in JSX tags as attributes在 React 渲染 DOM 中只需要一个createRoot
,我建议你在子组件中接收带有解构的参数,这些参数必须作为属性在 JSX 标签中传递
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.