React教程

React Props

Props代表"属性"。它们是只读组件。它是一个存储标记属性值的对象,其工作方式类似于HTML属性。它提供了一种将数据从一个组件传递到其他组件的方法。它类似于函数参数。Props以与函数中传递的参数相同的方式传递给组件。
Props是不可变的,因此我们无法从组件内部修改Props。在组件内部,我们可以添加称为props的属性。这些属性在组件中以 this.props 的形式提供,可用于在我们的render方法中呈现动态数据。
当您在组件中需要不可变数据时,必须在ReactJS项目的 main.js 文件中的 reactDom.render()方法中添加Props,并在需要的组件中使用它。可以在下面的示例中进行解释。

示例

App.js
import React, { Component } from 'react';
class App extends React.Component {
   render() { 
      return (
          <div>
          <h1> Welcome to { this.props.name } </h1>  
          <p> <h4> lidihuo is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. </h4> </p>        
          </div>
    );
   }
}
export default App;
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App name = "lidihuo!!" />, document.getElementById('app'));

默认Props

不必总是在reactDom.render()元素中添加Props。您还可以直接在组件构造函数上设置默认Props。可以在下面的示例中进行解释。

示例

App.js
import React, { Component } from 'react';
class App extends React.Component {
   render() { 
      return (
          <div>
              <h1>default Props Example</h1>
          <h3>Welcome to {this.props.name}</h3> 
          <p>lidihuo is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad.</p>        
          </div>
        );
    }
}
App.defaultProps = {
   name: "lidihuo"
}
export default App;
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App/>, document.getElementById('app'));

状态和Props

可以在您的应用中组合状态和Props。您可以在上级组件中设置状态,然后使用prop在子级组件中传递状态。可以在下面的示例中显示。

示例

App.js
import React, { Component } from 'react';
class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         name: "lidihuo",       
      }
   }
   render() {
      return (
         <div>
            <JTP jtpProp = {this.state.name}/>           
         </div>
      );
   }
}
class JTP extends React.Component {
   render() {
      return (
          <div>
              <h1>State & Props Example</h1>
              <h3>Welcome to {this.props.jtpProp}</h3>
              <p>lidihuo is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad.</p>
         </div>  
      );
   }
}
export default App;
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App/>, document.getElementById('app'));

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4