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 @   monkey-K  阅读(376)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示