11. react 组合与继承(插槽)

说明:react 的组合相当于 Vue 中的插槽。

本质: React 元素本质就是对象(object),可以将任何东西作为 props 进行传递。组件可以接受任意 props,包括基本数据类型,React 元素以及函数

1.  props.children -- 默认【插槽】: 组件内嵌套的 jsx 都会分配给 props.children 属性

function Dialog(props) {
  return (
    <div>
      {props.children} // 插槽,用来渲染组件中嵌套的所有 JSX
    </div>
  )
}

function WelcomeDialog(props) {
 // Dialog 组件中嵌套的子组件都会被分配给 props.children
return ( <Dialog> <div> hello react </div> <div> hello react..... </div> </Dialog> ) } ReactDOM.render( <WelcomeDialog />, document.getElementById('root') )

2. 具名插槽 : 通过属性 props 传递 jsx

function SplitPane (props) {
  return (
    <div>
      <div>{props.left}</div>
      <hr />
      <div>{props.right}</div>
    </div>
  )
}
function Left () {
  return (
    <div>
      left
    </div>
  )
}
function Right(props) {
  return (
    <div>
      right
    </div>
  )
}
function Contianer (props) {
 // 属性接收组件
return ( <SplitPane left={ <Right/>} right={ <Left /> }> </SplitPane> ) } ReactDOM.render( <Contianer />, document.getElementById('root') )

3. 也可以通过 class 的方式

function Dialog(props) {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        {props.title}
      </h1>
      <p className="Dialog-message">
        {props.message}
      </p>
      {props.children}
    </FancyBorder>
  );
}

class SignUpDialog extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSignUp = this.handleSignUp.bind(this);
    this.state = {login: ''};
  }

  render() {
    return (
      <Dialog title="Mars Exploration Program"
              message="How should we refer to you?">
        <input value={this.state.login}
               onChange={this.handleChange} />
        <button onClick={this.handleSignUp}>
          Sign Me Up!
        </button>
      </Dialog>
    );
  }

  handleChange(e) {
    this.setState({login: e.target.value});
  }

  handleSignUp() {
    alert(`Welcome aboard, ${this.state.login}!`);
  }
}

 

4. react 的继承不做 UI层渲染。跟JS 继承一样。

 

posted @ 2020-06-08 18:20  monkey-K  阅读(368)  评论(0编辑  收藏  举报