react 基础知识

基础知识

css-module

react 将js转为vdom,react-dom将vdom转为dom

// 外面一层是一个动态值,里面的表示的是对象
<img src={logo} style = {{width: 200px}} />

webpack里配置的如果要用模块化作用需要模块化导出,形式如下

模块化css模块很有必要,将 css 文件命名为xxx.module.css,引入的时候赋予其名称,在标签上使用时带上名称和css属性名即可。

import style from './index.module.css'

// use
<img src={logo} className={style.img} />

问题 :

  • 多个className如何实现
  • 公共样式和模块样式的使用
  • less语法的使用需要配置吗?

    Context

import React, {Component} from 'react';

// 创建上下文
const Context = React.createContext();

// 创建提供者
const Provider = Context.Provider;

// 创建消费者
const Consumer = Context.Consumer;

function Child(props) {
  return (
    <button onClick={() => {
      props.addNum();
    }}>
      {props.number}
    </button>
  );
}


class ContextApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      number: 0
    };
  }

  addNum = () => {
    this.setState({
      number: this.state.number + 1
    });
  };

  render() {
    return (
      <Provider value={{ number: this.state.number, addNum: this.addNum }}>
        <Consumer>
          {value =>
            <Child {...value}/>
          }
        </Consumer>
      </Provider>
    );
  }
}

export default ContextApp;

组件复合

类比于vue的插槽功能

import React from 'react';

function Slot(props) {
  return (
    <div>{props.children}</div>
  );
}

// 复合组件的使用
function Composition(props) {
  return (
    <div>
      <Slot>
        <h1>我是标题</h1>
        <h3>我是内容</h3>
      </Slot>
    </div>
  );
}

export default Composition;

jsx是一个对象,我们返回具有名称的复合组件子组件可以通过 props.children.xxx 获得

import React from 'react';


function Slot(props) {
  return (
    <div>
      {props.children.body}
      {props.children.footer}
    </div>
  );
}

// 复合组件的使用
function Composition(props) {
  return (
    <div>
      <Slot>
        {{
          body: (
            <>
              <h1>我是标题</h1>
              <h3>我是内容</h3>
            </>
          ),
          footer: (
            <>
              <h1>我是Footer</h1>
            </>
          )
        }}
      </Slot>
    </div>
  );
}

export default Composition;
import React from 'react';


function Slot(props) {
  const file = {
    one: { values: 'aaa', keys: 333 },
    two: { values: 'bbb', keys: 444 },
  };
  // 传递值给插槽处
  const { body, footer } = props.children(file[props.fileId]);
  return (
    <div>
      {body}
      {footer}
    </div>
  );
}

// 复合组件的使用
function Compons(props) {
  return (
    <div>
      <Slot fileId={'one'}>
        {
          ({ values, keys }) => ({
            body: (<><h1>我是标题</h1><h3>value: {values}--- key:{keys}</h3></>),
            footer: (<><h1>我是Footer</h1></>)
          })
        }
      </Slot>
    </div>
  );
}

export default Compons;

高阶组件

接收一个组件作为参数,返回一个组件

猜你喜欢

转载自www.cnblogs.com/daixixi/p/12405679.html