在同一页面上重用组件,每个组件都有自己的状态

时间:2018-03-13 17:55:47

标签: reactjs react-native

我试图在一个父组件下多次重复使用相同的组件。所有SortLabel都共享相同的状态。因此,当单击一个元素时,将反映前一次单击的状态。如何使它们成为具有独立状态的独立组件?

class SortLabel extends Component {

constructor(props, context) {
    super(props, context);
    this.state = {
        order: 'asc',
    };

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

toggle() {
    this.setState({order: this.state.order === 'asc' ? 'desc' : 'asc'});
}

render() {
    const {itemProperty, sortingProperty} = this.props;

    return (            
        <TableSortLabel
            key={`Sort ${itemProperty.get('id')}`}
            id={`Sort ${itemProperty.get('id')}`}
            active = {sortingProperty === itemProperty.get('id')}
            onClick = {this.toggle}
            direction={this.state.order}>
            {itemProperty.get('description')}
        </TableSortLabel>             
    )
 }
}

更新 在测试之后,组件具有单独的状态。问题是因为我处理状态的方式

1 个答案:

答案 0 :(得分:0)

它看起来像你设置它的方式,你绑定从父组件到子组件的相同变量(即id)。所以你只需要以某种方式将它分开:id1,id2等......以便更好地回答你的问题我可能希望看到父组件

相关问题