Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 views
in Technique[技术] by (71.8m points)

reactjs - Set component's props dynamically

I need to set component's props after it is stored in a variable, here is pseudo code:

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

        )
      })
    )
  }

Inside return I run a loop where I need to set props for the component that is stored inside a variable.... How to set props for this component which I stored earlier in a variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The proper way is to use React's cloneElement method (https://facebook.github.io/react/docs/react-api.html#cloneelement). You can achieve what you want by doing:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...