ReactJS - 属性 (props)



React 允许开发者使用属性创建动态和高级组件。每个组件都可以拥有类似于 HTML 属性的属性,并且每个属性的值都可以使用属性 (props) 在组件内部访问。

例如,具有名称属性的 Hello 组件可以通过 this.props.name 变量在组件内部访问。

<Hello name="React" />
// value of name will be "Hello* const name = this.props.name

React 属性支持不同类型的属性值。它们如下所示:

  • 字符串
  • 数字
  • 日期时间
  • 数组
  • 列表
  • 对象

使用 Props

当我们需要在组件中使用不可变数据时,我们只需将 props 添加到 reactDOM.render() 函数(在 main.js 中)并将其在组件内部使用即可。

App.jsx

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App headerProp = "Header from props..." contentProp = "Content
   from props..."/>, document.getElementById('app'));

export default App;

这将产生以下结果。

React Props Example

默认 Props

您还可以直接在组件构造函数上设置默认属性值,而不是将其添加到 reactDom.render() 元素中。

App.jsx

import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}
App.defaultProps = {
   headerProp: "Header from props...",
   contentProp:"Content from props..."
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

输出与之前相同。

React Props Example

状态与 Props

以下示例展示了如何在应用中组合 状态和 props。我们在父组件中设置状态,并使用 props 将其向下传递到组件树中。在 render 函数内部,我们设置了子组件中使用的 headerPropcontentProp

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         header: "Header from props...",
         content: "Content from props..."
      }
   }
   render() {
      return (
         <div>
            <Header headerProp = {this.state.header}/>
            <Content contentProp = {this.state.content}/>
         </div>
      );
   }
}
class Header extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}
export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

结果将再次与前两个示例相同,唯一不同的是我们数据源,现在它最初来自 状态。当我们想要更新它时,我们只需要更新状态,所有子组件都将更新。有关这方面的更多信息,请参阅事件章节。

React Props Example

让我们在本节中逐一学习以下概念。

广告

© . All rights reserved.