2016-11-29 73 views
1
 <div> 
    {this.props.data.map((res, index) => { 
     return (<div key={index}> 
     <div> 
      <span>{response.testData}</span> 
<a key={index} onClick={() => this.showExtraLine(index)}><span className={`btn-green ${this.state.showExtraLine ? 'active' : ''}`}></span></a> 
      { this.state.showExtraLine ? <span> 
      {res.abc[0].def} 
      </span> : '' } 
     </div> 
     </div> 
    ); 
    })} 
    </div> 
showExtraLine(e){ 
    this.setState({ 
     showExtraLine: !this.state. showExtraLine, 
    }); 
    } 

需要切換{res.abc [0] .def}部件上的點擊錨 - 切換作品,但不知道如何處理只切換相應的跨度 - 現在它隱藏所有的行..如何處理使用.map時的css切換?reactjs map和css class toggle

回答

0

我認爲這個問題是在你的狀態變量,您使用的是單一的狀態變量並打印該變量的狀態的基礎上,<span>。 而不是在showExtraLine()函數中使用狀態爲showExtraLine = [], 的數組,您正在傳遞索引,請使用該索引僅切換該元素。

試試這個它應該工作:

{this.props.data.map((res, index) => { 
    return (<div key={index}> 
    <div> 
     <span>{response.testData}</span> 
     <a key={index} onClick={() => this.showExtraLine(index)}><span className={`btn-green ${!this.state.showExtraLine[index] ? 'active' : ''}`}></span></a> 
     { !this.state.showExtraLine[index] ? 
     <span>{res.abc[0].def}</span> 
     : '' } 
    </div> 
    </div> 
); 
})} 

showExtraLine(index){ 
    let showExtraLine = this.state.showExtraLine.slice(0); 
    showExtraLine[index] = !showExtraLine[index]; 
    this.setState({ 
     showExtraLine: showExtraLine, 
    }); 
} 
0

現在您正在維護組件中所有映射元素的狀態,因此它們都引用相同的值。您應該改爲創建一個組件,以便用它們自己的狀態分別渲染每個映射元素。

class Parent extends React.Component { 
    render() { 
    return (
     <div> 
     {this.props.data.map((res, index) => <Child key={index} {...res} />)} 
     </div> 
    ); 
    } 
} 

class Child extends React.Component { 

    constructor(props) { 
    super(props); 
    this.state = { 
     showExtraLine: false 
    }; 
    this.showExtraLine = this.showExtraLine.bind(this); 
    } 

    render() { 
    return (
     <div> 
     <div> 
      <span>{this.props.testData}</span> 
      <a key={index} onClick={this.showExtraLine}> 
      <span className={`btn-green ${this.state.showExtraLine ? 'active' : ''}`}></span> 
      </a> 
      { this.state.showExtraLine ? <span>{this.props.abc[0].def}</span> : '' } 
     </div> 
     </div> 
    ); 
    } 

    showExtraLine(e){ 
    this.setState({ 
     showExtraLine: !this.state.showExtraLine 
    }); 
    } 
} 
+0

不唯一我的問題,我需要在這裏,還可以使用地圖1線我不認爲我應該mKing它做一個單獨的子組件 – monkeyjs

+0

映射仍將由父組件使用。創建子組件只是清理代碼,並允許爲數據數組中的每個元素維護一個單獨的可見狀態。 –