react change class name on state change

前端 未结 1 1348
野趣味
野趣味 2020-12-08 00:49

I have a state like this where I am setting active and class flag like this:

constructor(props) {
  super(props);
  this.state = {\         


        
1条回答
  •  攒了一身酷
    2020-12-08 00:54

    Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

    Explanation

    Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

    In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

    Example

    class Container extends React.Component {
      state = {
        activeIndex: null
      }
    
      handleClick = (index) => this.setState({ activeIndex: index })
    
      render() {
        return 
    } } class MyClickable extends React.Component { handleClick = () => this.props.onClick(this.props.index) render() { return } } ReactDOM.render(, document.getElementById('app'))
    button {
      display: block;
      margin-bottom: 1em;
    }
    
    .album>span:after {
      content: ' (an album)';
    }
    
    .active {
      font-weight: bold;
    }
    
    .active>span:after {
      content: ' ACTIVE';
    }
    
    
    

    Update: "Loops"

    In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

    // New render method for `Container`
    render() {
      const clickables = [
        { name: "a" },
        { name: "b" },
        { name: "c" },
      ]
    
      return 
    { clickables.map(function(clickable, i) { return } ) }
    }

    0 讨论(0)
提交回复
热议问题