码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-03-27 21:02:01      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:cli   tno   code   extends   build   higher   ati   gre   and   

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

标签:cli   tno   code   extends   build   higher   ati   gre   and   

原文地址:https://www.cnblogs.com/Answer1215/p/10610597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!