如何在ReactJS中引用特定对象作为属性传递
ReactJS是一个流行且著名的用于开发网站的JavaScript库。ReactJS的一个关键特性是能够从父组件传递属性到子组件,这被称为Props(属性)。Props是ReactJS库的重要特性之一,它允许组件从其父组件中访问数据。Props是只读的,这意味着子组件无法修改Props。父组件将Props作为属性传递给子组件,子组件可以使用”this.props”来访问Props。
React.js库有两种组件:
- 函数组件
- 类组件
让我们通过一个示例来了解如何在函数组件中引用特定对象作为属性传递:
步骤1: 创建一个React应用程序并使用以下命令安装模块:
npx create-react-app projectfoldername
步骤2: 使用以下命令进入项目文件夹:
cd projectfoldername
项目结构
步骤3: 现在,要引用一个特定的对象来传递属性,您首先需要在组件的代码中创建该对象并将其赋值给一个变量。然后,您可以将此对象作为属性传递给子组件。为此,在src文件夹中的app.js文件中编写以下代码。
// React functional component here
// act as a parent component
function App() {
// The data we will send as props
// in child component
const userData = {
name: "Geeks for Geeks",
age: 20,
email: "geeksforgeeks@example.com",
};
return (
<div>
<h1>User Profile</h1>
<Profile data={userData} />
</div>
);
}
// React functional compont here works as
// a child compont accepting the props
function Profile(props) {
return (
<div>
<h2>{props.data.name}</h2>
<p>Age: {props.data.age}</p>
<p>Email: {props.data.email}</p>
</div>
);
}
// Exporting the component
export default App;
在上面的代码中,我们将Profile作为一个子组件,并从App组件中将用户数据传递给Profile组件,在Profile组件中我们可以通过props访问对象数据。 步骤4: 使用以下命令运行代码:
npm start
输出:
现在,让我们通过一个示例来了解如何引用特定对象作为类组件中的属性传递下去:
- 按照上述步骤设置项目。
- 假设您有一个名为App的父组件,它有一个名为person的对象作为其状态。
- 现在,在ChildComponent中,我们可以使用传递给它的props访问person对象,并根据需要渲染其属性。
import React, { Component } from "react";
// React class component here act
// as a parent component
class App extends Component {
// state we will send in child component
state = {
person: {
name: "Geeks for Geeks",
age: 23,
email: "gfg@example.com",
},
};
render() {
const { person } = this.state;
return (
<div>
<h1>App Component</h1>
// sending the state in child component
<ChildComponent person={person} />
</div>
);
}
}
// React class component here act as a child component
class ChildComponent extends Component {
render() {
const { name, age, email } = this.props.person;
return (
<div>
<h2>Child Component</h2>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>Email: {email}</p>
</div>
);
}
}
// Exporting the component
export default App;
通过这种方式,我们可以引用一个特定的对象作为类组件中要传递的属性。
输出: