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 继承一样。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值