ReactJs 专题
您的位置:JS框架 > ReactJs专题 > ReactJS props简介
ReactJS props简介
作者:--    发布时间:2019-11-20

propsstate的主要区别是props是不变的。 这就是为什么容器组件应该定义可以更新和更改的状态,而子组件只应该使用props来传递状态数据。

使用props

当我们在组件中需要不可变的数据时,可以在main.js中添加propsreactdom.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>
      );
   }
}
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;

这将产生以下结果 -

默认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'));

输出和以前一样 -

state 和 props

以下示例显示如何在应用程序中组合stateprops。 在父组件中设置状态并使用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'));

结果会和前面两个例子一样,唯一不同的是我们数据的来源,现在来自state。 当想更新它时,只需要更新状态,所有的子组件都会被更新。 更多关于这个在事件章节。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册