React向组件内部动态传入带内容的结构

编程入门 行业动态 更新时间:2024-10-28 20:23:16

React向<a href=https://www.elefans.com/category/jswz/34/1771375.html style=组件内部动态传入带内容的结构"/>

React向组件内部动态传入带内容的结构

  • children props:通过组件标签体传入结构

    <A><B>xxx</B>
    </A>
    {this.props.children}
    
  • render props:通过组件标签属性传入结构,一般用render函数属性

    <A render={data=> <C data={data}></C>}></A>
    //A组件:
    {this.props.render(内部state数据)}
    //C组件:读取A组件传入的数据显示
    {this.props.data}

    案例

    import React, { Component } from 'react'
    import './index.css'export default class Parent extends Component {render() {return (<div className='parent'><h4>Parent组件</h4><A render={(name) => <B name={name}></B> }></A></div>)}
    }class A extends Component {state = {name:'sun'}render() {return (<div className='A'><h4>A组件</h4>{/* {this.props.children} */}{this.props.render(this.state.name)}</div>)}
    }class B extends Component {render() {return (<div className='B'><h4>B组件</h4><div>B组件收到的name为:{this.props.name}</div></div>)}
    }

    样式文件:

    .parent{width: 500px;background-color: greenyellow;padding: 20px;
    }.A{width: 90%;background-color: skyblue;padding: 20px;
    }.B{width: 90%;background-color: slateblue;padding: 20px;
    }

    运行结果:

更多推荐

React向组件内部动态传入带内容的结构

本文发布于:2023-11-15 19:49:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605319.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   结构   动态   内容   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!