小编典典

动态设置组件的道具

reactjs

将组件存储在变量中后,需要设置组件的道具,这是伪代码:

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

        )
      })
    )
  }

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


阅读 253

收藏
2020-07-22

共1个答案

小编典典

正确的方法是使用React的cloneElement方法(https://facebook.github.io/react/docs/react-
api.html#cloneelement)。您可以通过执行以下操作来实现所需的目标:

<span>
  {
    React.cloneElement(
      component,
      {title: item.title}
    )
  }
</span>
2020-07-22