react组件

传递props

import React, {Component, VFC, ReactNode } from 'react';

const Hello: VFC<{ body: ReactNode }> = ({ body }) => {
  return <div>{body}</div>;
};

class App extends Component {
  render() {
    return (
      <>
        <Hello body={'hello ajanuw'}/>
        <Hello body={ <h1>hello ajanuw</h1> }/>
      </>
    );
  }
}

export default App;

传递 children

import React, {FC, Component} from 'react';

const Hello: FC<{}> = ({ children }) => {
  return <div>{children}</div>;
};

class App extends Component {
  render() {
    return (
      <>
        <Hello>hello ajanuw</Hello>
        <Hello><h1>hello ajnauw</h1></Hello>
      </>
    );
  }
}

export default App;

高阶组件

import React, {Component} from 'react';

const createHello = (Root)=>(
  class Hello extends Component {
    state = {
      body: 'hello ajanuw'
    }
    render(){
      return(<Root {...this.props} body={this.state.body}/>);
    }

    componentDidMount(){
      setTimeout(()=>{
        this.setState({body: 'hello world'})
      }, 2000);
    }
  }
);

const Body = ({body})=> <div>{ body }</div>;
const Hello = createHello(Body);

class App extends Component {
  render() {
    return (
      <>
        <Hello />
      </>
    );
  }
}

export default App;

将函数作为children传递给组件

import React, {Component} from 'react';
const Hello = ({children})=>{
  return <div>{children.a} {children.b}</div>
}
class App extends Component {
  state = {
    body: {
      a: 'hello',
      b: 'world'
    }
  }
  render() {
    return (
      <>
        <Hello>{ this.state.body }</Hello>
      </>
    );
  }
}
export default App;
import React, {Component} from 'react';

const Hello = ({children})=>{
  return <div>{ children(Math.random()) }</div>
}

const getBody = num =>num > 0.5 ? 'hello ajanuw' : 'hello react';
class App extends Component {
  render() {
    return (
      <>
        <Hello>{ num => getBody(num) }</Hello>
      </>
    );
  }
}

export default App;

获取到异步数据后在渲染

import React, {Component} from 'react';

class Hello extends Component {
  state = {
    body: null
  }
  render(){
   if(this.state.body === null) return null;
   return(
     <h1>{this.props.children(this.state.body)}</h1>
   );
  }

  componentDidMount(){
    setTimeout(()=>
      this.setState({ body: 'hello ajanuw' }), 2000);
  }
}

class App extends Component {
  render() {
    return (
      <>
        <Hello>{data => <p>{ data }</p>}</Hello>
      </>
    );
  }
}

export default App;

受控输入和非受控输入

<input type='text' value={ this.state.value } /> // 受控
<input type='text' defaultValue={ this.state.value } /> // 非受控
posted @ 2018-08-27 16:35  Ajanuw  阅读(269)  评论(0编辑  收藏  举报