加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 动态设置组件的道具

发布时间:2020-12-15 20:43:59 所属栏目:百科 来源:网络整理
导读:我需要在组件存储在变量中之后设置它的道具,这里是伪代码: render(){ let items = [{title:'hello'},{title:'world'}]; let component = false; switch (id) { case 1: component = A / break; case 2: component = B / break; } return( items.map((item,i
我需要在组件存储在变量中之后设置它的道具,这里是伪代码:
render(){

    let items = [{title:'hello'},{title:'world'}];
    let component = false;

    switch (id) {
      case 1:
        component = <A />
        break;
      case 2:
        component = <B />
        break;      
    }

    return(
      items.map((item,index)=>{
        return(
          <span>
            {/* SOMETHING LIKE THIS WOULD BE COOL - IS THAT EVEN POSSIBLE*/}
            {component.props.set('title',item.title)}
          </span>11

        )
      })
    )
  }

在内部返回我运行一个循环,我需要为存储在变量中的组件设置道具….如何设置我之前存储在变量中的组件的道具?

正确的方法是使用React的cloneElement方法( https://facebook.github.io/react/docs/react-api.html#cloneelement).
您可以通过以下方式实现您想要的目标:
<span>
  {
    React.cloneElement(
      component,{title: item.title}
    )
  }
</span>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读