[React] Use React.ReactNode for the children prop in React TypeScript components and Render Props(代码

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;
};

 

以上是关于[React] Use React.ReactNode for the children prop in React TypeScript components and Render Props(代码的主要内容,如果未能解决你的问题,请参考以下文章

React Hooks: use modal

[React] Use the React Effect Hook in Function Components

[React] Use React Context to Manage Application State Through Routes

[React] Use React.cloneElement to Modify and Add Additional Properties to React Children

扩展 eslint-config-react-app 时 no-use-before-define 无效

[React] Use the URL as the source of truth in React