zoukankan      html  css  js  c++  java
  • [React] Use React.ReactNode for the children prop in React TypeScript components and Render Props

    Because @types/react has to expose all its internal types, there can be a lot of confusion over how to type specific patterns, particularly around higher order components and render prop patterns. The widest and most recommended element type is React.ReactNode, and we build up to it by explaining the edge cases.

    For render prop:

    type ButtonProps = {
      label?: string;
      children: (b: boolean) => React.ReactNode;
    };
    function App() {
      return (
        <Button>
          {isOn => (isOn ? <div> Turn off</div> : <div> Turn on</div>)}
        </Button>
      );
    }
    type ButtonProps = {
      label?: string;
      children: React.ReactNode;
    };
    type ButtonState = {
      isOn: boolean;
    };
    class Button extends React.Component<ButtonProps, ButtonState> {
      static defaultProps = {
        label: "Hello World!"
      };
      state = {
        isOn: false
      };
    
      toggle = () => this.setState({ isOn: !this.state.isOn });
    
      render() {
        const { label, children } = this.props;
        const { isOn } = this.state;
        const style = {
          backgroundColor: isOn ? "red" : "green"
        };
        return (
          <button style={style} onClick={this.toggle}>
            {children(isOn)}
          </button>
        );
      }
    }

    For React children projection:

    type ButtonProps = {
      label?: string;
      children: React.ReactNode;
    };
  • 相关阅读:
    对list集合中的对象进行排序(转载)
    关键字的作用
    CocoaPods的 安装 /卸载/升级
    block基本使用和底层
    程序启动 - 类调用的方法
    成员变量修饰词的作用
    宏(define)与常量(const)
    iOS
    监听网络状态
    nil、Nil、NULL与NSNull的区别及应用
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10610597.html
Copyright © 2011-2022 走看看