How to assign refs to multiple components

前端 未结 4 1336
萌比男神i
萌比男神i 2020-11-27 20:26

I\'m using React to render multiple data using array.map.
How can disable the clicked button from the list?

This is my code:

  onRun         


        
4条回答
  •  清酒与你
    2020-11-27 20:46

    Like @ShubhamKhatri's answer using ref is an option. You can also achieve desired behavior with state too.

    Example (Single Disabled Button Option)

    class App extends Component{
      constructor() {
        super();
        this.state = {
          disabled: ''
        };
      }
    
      onRunClick(act, index, e) {
        this.setState({ disabled: act._id });
      }
    
      render() {
        return (
          
    { this.state.acts.map((act, index) => { let boundActRunClick = this.onRunClick.bind(this, act, index); return (

    Name: {act.name}, URL(s): {act.urls}

    ) }) }
    ); } }

    Example (Multiple Disabled Button Option)

    class App extends Component{
      constructor() {
        super();
        this.state = {
          buttons: {}
        };
      }
    
      onRunClick(act, index, e) {
        this.setState((prevState) => { 
          const buttons = Object.assign({}, prevState.buttons, { [act._id]: !prevState.buttons[act._id] });
          return { buttons };
        });
      }
    
      render() {
        return (
          
    { this.state.acts.map((act, index) => { let boundActRunClick = this.onRunClick.bind(this, act, index); return (

    Name: {act.name}, URL(s): {act.urls}

    ) }) }
    ); } }

提交回复
热议问题