【八股系列】React中props和state的区别是什么?

Reactpropsstate的区别是:

  1. props是用来从父组件向子组件 进行传递数据的,在子组件中可以用props来接收到父组件传递过来的参数。
  2. props不可变 的,用户不能在子组件中修改props的值,因为从父组件中传递过来的值被认为是不可变数据。
  3. state表示的组件的内部状态 ,是私有数据
  4. state可变 的,用户可以通过setState等来修改数据 ,且React会根据state的修改重新进行组件的渲染。

示例代码:

js 复制代码
// 父组件
class ParentComponent extends React.Component {
  render() {
    return (
      <ChildComponent name="John" age={25} />
    );
  }
}

// 子组件
class ChildComponent extends React.Component {
  render() {
    return (
      <div>
        <p>Name: {this.props.name}</p>
        <p>Age: {this.props.age}</p>
      </div>
    );
  }
}

// 父组件
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
      </div>
    );
  }
}
相关推荐
岛泪14 分钟前
把 el-cascader 的 options 平铺为一维数组(只要叶子节点)
前端·javascript·vue.js
摘星编程28 分钟前
React Native for OpenHarmony 实战:SecureStorage 安全存储详解
安全·react native·react.js
lendsomething31 分钟前
graalvm使用实战:在java中执行js脚本
java·开发语言·javascript·graalvm
Kiyra1 小时前
阅读 Netty 源码关于 NioEventLoop 和 Channel 初始化部分的思考
运维·服务器·前端
冰暮流星1 小时前
javascript的switch语句介绍
java·前端·javascript
小简GoGo2 小时前
前端常用设计模式快速入门
javascript·设计模式
做科研的周师兄2 小时前
【MATLAB 实战】|多波段栅格数据提取部分波段均值——批量处理(NoData 修正 + 地理信息保真)_后附完整代码
前端·算法·机器学习·matlab·均值算法·分类·数据挖掘
da_vinci_x2 小时前
图标量产:从“手绘地狱”到“风格克隆”?Style Reference 的工业化实战
前端·游戏·ui·prompt·aigc·设计师·游戏美术
利刃大大2 小时前
【ES6】变量与常量 && 模板字符串 && 对象 && 解构赋值 && 箭头函数 && 数组 && 扩展运算符 && Promise/Await/Async
开发语言·前端·javascript·es6
天若有情6732 小时前
ES6 模块与 CommonJS 的区别详解
前端·javascript·es6