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


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

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

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

function Dialog(props) {
  return (
    
{props.children} // 插槽,用来渲染组件中嵌套的所有 JSX
) } function WelcomeDialog(props) {
 // Dialog 组件中嵌套的子组件都会被分配给 props.children
return (
hello react
hello react.....
) } ReactDOM.render( , document.getElementById('root') )

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

function SplitPane (props) {
  return (
    
{props.left}

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

3. 也可以通过 class 的方式

function Dialog(props) {
  return (
    
      

{props.title}

{props.message}

{props.children}
); } 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 ( message="How should we refer to you?"> this.state.login} onChange={this.handleChange} /> ); } handleChange(e) { this.setState({login: e.target.value}); } handleSignUp() { alert(`Welcome aboard, ${this.state.login}!`); } }

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