React props属性【七日打卡】

1,009 阅读2分钟

如果需要在组件之间进行传值,那么props属性就起到了这个作用,在React中props和state是两个非常重要的属性。

state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。

Note:属性是用于设置默认值,不改变的值使用props,而改变的值我们要使用state.

  1. 每个组件对象都会有props(properties的简写)属性;
  2. 组件标签的所有属性都保存在props中;
  3. 内部读取某个属性值:this.props.propertyName;
  4. 作用:通过标签属性从组件外向组件内传递数据(只读 read only);
  5. 对props中的属性值进行类型限制和必要性限制;
Person.propTypes = {
      name: React.PropTypes.string.isRequired,
      age: React.PropTypes.number.isRequired
 }
  1. 扩展属性:将对象的所有属性通过props传递
<Person {...person}/>
  1. 默认属性值
Person.defaultProps = {
      name: 'Mary'
};

Demo

/*
   1. 拆分组件: 拆分界面, 抽取组件
     * 单个标题组件: Welcome
     * 应用组件: App
   2. 分析确定传递数据和数据类型
     * Welcome: props.name  string
     * App: props.names    array
   */

  //定义内部标题组件
  class Welcome extends React.Component {
    render() {
      return <h2>Welcome {this.props.name}!</h2>;
    }
  }
  Welcome.propTypes = {
    name: React.PropTypes.string.isRequired
  };
  //定义外部应用组件
  class App extends React.Component {
    render() {
      return (
        <div>
          {
            this.props.names.map(
              (name, index) => <Welcome name={name} key={index}/>
            )
          }
        </div>
      );
    }
  }
  App.propTypes = {
    names: React.PropTypes.array.isRequired
  };

  var names = ['Tom', 'Jack', "Bob"];
  ReactDOM.render(<App names={names}/>, document.getElementById('example'));

拓展阅读 create-react-app关闭eslint提醒

前言

在项目开发过程中,有时候苦恼于eslint的校验规则,例如变量定义为使用、空格等的校验。

主要有两种方式可实现关闭eslint提醒。

第一种方式

在react-scripts依赖包下的config目录找到webpack.config.js配置文件,在webpack.config.js中注释掉以下代码:

{
          test: /\.(js|mjs|jsx|ts|tsx)$/,
          enforce: 'pre',
          use: [
            {
              options: {
                cache: true,
                formatter: require.resolve('react-dev-utils/eslintFormatter'),
                eslintPath: require.resolve('eslint'),
                resolvePluginsRelativeTo: __dirname,
                // @remove-on-eject-begin
                ignore: isExtendingEslintConfig,
                baseConfig: isExtendingEslintConfig
                  ? undefined
                  : {
                      extends: [require.resolve('eslint-config-react-app')],
                    },
                useEslintrc: isExtendingEslintConfig,
                // @remove-on-eject-end
              },
              loader: require.resolve('eslint-loader'),
            },
          ],
          include: paths.appSrc,
        },

第二种方式

package.json 中修改为以下:

eslintConfig": {
    "extends": "react-app",
    "rules": {
      "no-undef": "off",
      "no-restricted-globals": "off",
      "no-unused-vars": "off"
    }
  }

然后重启npm start。