简体   繁体   English

如何在 React 中单击动态添加的按钮时触发 function?

[英]How to fire a function on clicking by a dynamically added button in React?

I have a React app with a component that has a button to add a list of dynamic buttons.我有一个带有一个组件的 React 应用程序,该组件具有一个添加动态按钮列表的按钮。 Each dynamic button has the onClick method to fire a function (sendOption) with an id parameter.每个动态按钮都有 onClick 方法来触发带有 id 参数的 function (sendOption)。 The problem is, the function "sendOption" is not firing after clicking on the added button.问题是,单击添加的按钮后,function“sendOption”没有触发。

I also changed this:我也改变了这个:

<button onClick={this.sendOption(buttonId)}>

to this:对此:

<button onClick={() => this.sendOption(buttonId)}>

but still, the onClick is not working.但是,onClick 仍然无法正常工作。 How can I solve this?我该如何解决这个问题?

Component:零件:

let buttonId = 0;

Class ButtonCreation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buttonsList: [],
        }
    }

    addButton = () => {
        buttonId += 1;

        this.setState({ 
             buttonsList: [...this.state.buttonsList, <button onClick={this.sendOption(buttonId)}>Send Option</button>]
        })
    }

    sendOption = (buttonId) => {
       console.log(buttonId)
    }

    render() {
       return(
          <div>
            <button onClick={this.addButton}>Add new Button</button>
            {this.state.buttonsList}
          </div>
       );
    }
}

export default ButtonCreation;

The issue is with click event binding:问题在于点击事件绑定:

Change this:改变这个:

onClick={this.sendOption(buttonId)}

To:至:

onClick={() => this.sendOption(buttonId)}

NOTE:笔记:

on button click, it will not print right id with that button, but prints last buttonId always, I have also solved that issue.Another issue with you code is when the user clicks on any, with this:单击按钮时,它不会使用该按钮打印正确的 id,但始终打印最后一个buttonId ,我也解决了该问题。您的代码的另一个问题是当用户单击任何按钮时,使用以下命令:

<button value={buttonId} onClick={(e) => this.sendOption(e.target.value)}>Send Option</button>


You can run the code snippet and check:您可以运行代码片段并检查:

 let buttonId = 0; class App extends React.Component { constructor(props) { super(props); this.state = { buttonsList: [] } } addButton = () => { buttonId += 1; this.setState({ buttonsList: [...this.state.buttonsList, <button value={buttonId} onClick={(e) => this.sendOption(e.target.value)}>Send Option</button>] }) } sendOption = (buttonId) => { console.log(buttonId) } render() { return( <div> <button onClick={this.addButton}>Add Button </button> <br/><br/> {this.state.buttonsList} </div> ); } } ReactDOM.render(<App />, document.getElementById('react-root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react-root"></div>

Try this:尝试这个:

import React from "react";
import "./styles.css";

let buttonId = 0;
export default class App extends React.Component {
  constructor(props) {
  super(props);
  this.state = {
    buttonsList: []
  };
 }

addButton = () => {
   buttonId += 1;

  this.setState({
    buttonsList: [
      ...this.state.buttonsList,
      <button id={buttonId} onClick={(e) => this.sendOption(e)}>Send Option</button>
    ]
  });
};

sendOption = e => {
  console.log(e.target.id);
};

render() {
      return (
      <div>
        <button onClick={this.addButton}>Add new Button</button>
        {this.state.buttonsList}
      </div>
    );
  }
}

code pen: https://codesandbox.io/s/clever-flower-7fm05?file=/src/App.js代码笔: https://codesandbox.io/s/clever-flower-7fm05?file=/src/App.js

here is an example for each button with each id:这是每个 id 的每个按钮的示例:

use target.id for getting each button ID by click use key for avoiding DOM key Problem使用target.id通过单击获取每个按钮 ID 使用来避免 DOM 键问题

let buttonId = 0;
export default function App() {
  const [buttonsList, setbuttonsList] = useState([]);

  const addButton = () => {
    buttonId += 1;

    setbuttonsList(prevState => [
      ...prevState,
      <button
        key={buttonId}
        id={buttonId}
        onClick={event => sendOption(event, event.target.id)}
      >
        Send Option
      </button>
    ]);
  };

  const sendOption = (event, id) => {
    console.log(id);
  };

  return (
    <div>
      <button onClick={addButton}>Add new Button</button>
      {buttonsList}
    </div>
  );
}

code [ https://codesandbox.io/s/vigorous-firefly-c7nrc?fontsize=14&hidenavigation=1&theme=dark]代码 [ https://codesandbox.io/s/vigorous-firefly-c7nrc?fontsize=14&hidenavigation=1&theme=dark]

Your problem is almost solved by @Vivek. @Vivek 几乎解决了您的问题。

But there are few points that I wanted to suggest you in your code.但是我想在您的代码中向您建议几点。 You will get better idea by looking at the following code snippet:通过查看以下代码片段,您将获得更好的主意:

 class App extends React.Component { constructor(props) { super(props); this.state = { buttonsList: [], btnCounter: 0, } } addButton = () => { // you can pass name, value for new button based on some value // you can also generate new id every time: const id = new Date().getTime(); // use functional setState whenever update previous state this.setState((prevState) => ({ btnCounter: prevState.btnCounter + 1, buttonsList: [...prevState.buttonsList, { id: prevState.btnCounter + 1, name: `Name${prevState.btnCounter + 1}`, value: `Send Option` }] })); // if possible add properties of button instead of directly adding element into state } sendOption = (buttonId) => { console.log(buttonId) } render() { const { buttonsList } = this.state; return ( <div> <button onClick={this.addButton}>Add new Button</button> {buttonsList && buttonsList.length > 0 && buttonsList.map((btn, i) => ( <div key={btn.id}> <button name={btn.name} onClick={() => this.sendOption(btn.id)} > {btn.value} </button> </div> ))} </div> ); } } ReactDOM.render(<App />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM