2017-10-17 70 views
0

我怎麼可以創建基於道具或初始狀態值傳遞多個元素傳遞的值作出反應。如何創建多個標籤的基礎上,通過道具

constructor(props, context) { 
    this.state = { 
     numberOfElements: this.props.numberOfElements || 6 
    } 

render() { 
    return (
     <div> 
      {/*Six elements if not passed through props*/} 
      span 
      span 
      ... 
      span 
     </div> 
    ) 
} 

是否有React.method可用於此目的?

回答

1

使用元素的數組來呈現多個元素

constructor(props, context) { 
    this.state = { 
     numberOfElements: this.props.numberOfElements || 6 
    } 

renderElements(){ 
    let elements = []; 
    let total = this.props.numberOfElements || this.state.numberOfElements; 
    for(let i = 0;i < total;i++){ 
    elements.push(<span>Hello</span>) 
    } 
    return elements; 
} 

render() { 
    return (
     <div> 
      {this.renderElements()} 
     </div> 
    ) 
} 
1

你應該使用數組迭代和創建元素。
的一種方法是:

render() { 
    const myArray = new Array(this.state.numberOfElements).fill('bar'); // array with 6 members ("bar") 
    return (
     <div> 
      {myArray.map(i=><span>foo</span>)} 
     </div> 
    ) 
} 

運行例如:

class App extends React.Component { 
 
    constructor(props){ 
 
    super(props); 
 
    this.state = { 
 
     numberOfElements: this.props.numberOfElements || 6 
 
    } 
 
    } 
 
    render() { 
 
    const myArray = new Array(this.state.numberOfElements).fill('bar'); 
 
    return (
 
     <div> 
 
     {myArray.map(i => <div>foo</div>)} 
 
     </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="root"></div>

+0

@VonAxt如果這個答案或其他任何一個解決您的問題,請標記爲接受 –