2017-07-31 34 views
0

我有一個引導網格,其中每個網格物體都從一個對象數組填充,但在每個網格物體之後我想要一個投票按鈕。我怎樣才能在每個按鈕上單獨維護狀態,即點擊按鈕1時,文本應該從「投票」變爲「投票」,而其他人保持爲「投票」。如何處理多個按鈕的狀態與反應?

目前一個按鈕被按下時,所有的人都變成「投票」

class Items extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { hasVoted: false }; 

     this.OnClick = this.OnClick.bind(this); 
    } 

    OnClick() { 
     this.setState(prevState => ({ 
      hasVoted: !prevState.hasVoted 
     })); 
    } 

    render() { 
     const Item = teasers.items.map(item => 
      <Col key={item.nid}> 
       <span> 
        {itemType} 
       </span> 

       <a href={item.path}> 
        <Image src={item.image.src} title={item.productType} /> 
        <span> 
         {item.Title} 
        </span> 
        <div className={teasersStyle.copy}> 
         {" "}{item.Copy}> 
        </div> 
       </a> 

       <div 
        className={this.state.hasVoted ? "active" : "notactive"} 
        onClick={this.OnClick} 
       > 
        {this.state.hasVoted ? "Voted" : "Vote"} 
       </div> 
      </Col> 
     ); 
     return (
      <div> 
       <Grid> 
        <Row> 
         {Item} 
        </Row> 
       </Grid> 
      </div> 
     ); 
    } 
} 

export default Items; 
+0

使'hasVoted'成爲每個項目的屬性。 –

+0

@IngoBürk不知道我確切地理解你的意思。像這樣:hasVoted = {this.state.hasVoted} –

+0

你可以讓你的按鈕有狀態,或者你可以將它們的'hasVoted'狀態存儲在'Items'狀態中作爲一個布爾值數組,其索引與'teasers中的按鈕索引匹配.items'。然後,當您映射'teasers.items.map((item,index)=> {...})'時,您可以使用索引訪問'hasVoted'狀態並將該屬性應用於按鈕。順便說一句:您正在使用'this.handleOnClick',但您的方法名爲'OnClick()'。 –

回答

2

我已經爲您創建一個簡單的例子:

class App extends React.Component { 
    constructor() { 
     super(); 
     this.onClick = this.onClick.bind(this); 
     this.state = { 
      arr: [ 
       { name: "first", isActive: true }, 
       { name: "second", isActive: true }, 
       { name: "third", isActive: true }, 
       { name: "fourth", isActive: true } 
      ] 
     }; 
    } 
    onClick(index) { 
     let tmp = this.state.arr; 
     tmp[index].isActive = !tmp[index].isActive; 
     this.setState({ arr: tmp }); 
    } 
    render() { 
     return (
      <div> 
       {this.state.arr.map((el, index) => 
        <div key={index} onClick={() => this.onClick(index)}> 
         name: {el.name}/isActive: {el.isActive ? "true" : "false"} 
        </div> 
       )} 
      </div> 
     ); 
    } 
} 

檢查fiddle並實施在你的情況。

+0

感謝安德魯,偉大的工作,但有一個簡單的方法,讓其他人點擊時,所有其他人失誤? –

+0

@ChrisO,勾選https://jsfiddle.net/69z2wepo/83671/ – Andrew

+0

非常感謝Andrew –