我现在有两个按钮,我想在点击一个按钮后得到一个按钮的值。
现场演示代码框:获取按钮值
我试过以下几种方法。
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [position, setPosition] = useState("");
const handleNextStep = (e) => {
console.log("label", e.target.innerHTML);
console.log("label", e.target.innerHTML);
};
return (
<div className="App">
<h1>Hello Click the buttons bellow</h1>
<div className="btn-group my-3 d-flex justify-content-center align-items-center">
<button
type="button"
className={`btn btn-sm mx-2 ${
position === "BottomLeft" ? "btn-info text-white" : "btn-lightDark"
}`}
onClick={() => {
setPosition(position !== "BottomLeft" ? "BottomLeft" : "");
handleNextStep();
}}
>
Bottom Left
</button>
<button
type="button"
className={`btn btn-sm mx-2 ${
position === "BottomRight" ? "btn-info text-white" : "btn-lightDark"
}`}
onClick={() => {
setPosition(position !== "BottomRight" ? "BottomRight" : "");
handleNextStep();
}}
>
Bottom Right
</button>
</div>
</div>
);
}
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [position, setPosition] = useState("");
const handleNextStep = (e) => {
console.log("label", e.target.innerHTML);
console.log("label", e.target.innerHTML);
};
return (
<div className="App">
<h1>Hello Click the buttons bellow</h1>
<div className="btn-group">
<button
type="button"
className={`btn btn-sm mx-2 ${
position === "BottomLeft" ? "btn-info" : "btn-lightDark"
}`}
onClick={() => {
setPosition(position !== "BottomLeft" ? "BottomLeft" : "");
handleNextStep();
}}
>
Bottom Left
</button>
<button
type="button"
className={`btn btn-sm mx-2 ${
position === "BottomRight" ? "btn-info" : "btn-lightDark"
}`}
onClick={() => {
setPosition(position !== "BottomRight" ? "BottomRight" : "");
handleNextStep();
}}
>
Bottom Right
</button>
</div>
</div>
);
}但我得到了错误:react-dom.development.js:327 Uncaught TypeError: Cannot read property 'target' of undefined。
这里怎么了?
发布于 2021-03-15 20:28:47
我认为“值”指的是<button>标记中的内容。在这种情况下,您需要:
const handleNextStep = (e) =>{
console.log('label', e.target.innerHTML)
}而且,我也不知道你如何得到react-dom.development.js:327 Uncaught TypeError: Cannot read property 'target' of undefined。您应该只获得一个空字符串或undefined。
只是一个边节点:e.target.innerText也可以工作。
基于更新的
handleNextStep = (e) => {期待的是不发送的偶数,所以只需要将单击事件向下传递到代理函数中:
<div className="btn-group">
<button
type="button"
className={`btn btn-sm mx-2 ${
position === "BottomLeft" ? "btn-info" : "btn-lightDark"
}`}
onClick={(e) => {
setPosition(position !== "BottomLeft" ? "BottomLeft" : "");
handleNextStep(e);
}}
>
Bottom Left
</button>
<button
type="button"
className={`btn btn-sm mx-2 ${
position === "BottomRight" ? "btn-info" : "btn-lightDark"
}`}
onClick={(e) => {
setPosition(position !== "BottomRight" ? "BottomRight" : "");
handleNextStep(e);
}}
>
Bottom Right
</button>
</div>https://codesandbox.io/s/weathered-https-s0y2x?file=/src/App.js
https://stackoverflow.com/questions/66645114
复制相似问题