简体   繁体   中英

How to get button value on click in reactJs?

I have a button I'm using functional component in reactJs and i want to get button value on click, how can i get this?

My Code:-

 const Forms = () => { const handleClick =(event) =>{ const getSameValue = event.target.value console.log(getSameValue); } return ( <button onClick={handleClick}>Test</button> ); };

Thanks for your Efforts!

What you're doing would mostly work, although you want currentTarget , not target (you'd see the difference if your button had a span around its text), but your button doesn't have any value attribute, so its value is "" . The value of an input or button is accessed via the value attribute (and optionally, for some kinds of input , valueAsNumber or valueAsDate ). Your button has text content, but no value.

 const Forms = () => { const handleClick =( event) => { const theValue = event.currentTarget.value; console.log("the value:", theValue); const theText = event.currentTarget.textContent; console.log("the text: ", theText); }; return ( <button value="this is the value" onClick={handleClick}>Test</button> ); }; ReactDOM.render(<Forms />, document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

您必须在按钮标签上定义一个“值”属性,例如:

<button value='button value' onClick={handleClick}>Test</button>

You should add a value attribute to the button component and either use hooks or state to set the value and access it throughout the function/class.

Adding value attribute to the button:

<button value="someVal" onClick={handleClick}>Test</button>

Create and store button value using hooks

const [btn,btnVal] = useState("")

handleClick

const handleClick =(event) =>{
    const getSameValue = event.currentTarget.value
    btnVal(getSameValue)
  }

For class-based components:


export default class App extends React.Component {
  //const [count, setCount] = useState("");
 constructor(){
  super()
  this.state={
    val:""
  }
 }

 handleClick = (event) =>{
  this.setState({val:event.currentTarget.value})
 }

 render(){
  return (
    <div>
      <p>Button value: {this.state.val}</p>
      <button value="abcd" onClick={this.handleClick}>
        Click me
      </button>
    </div>
  );
  }
}

Further, you could access the button's value directly using the state or hook variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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