很抱歉,如果这个话题可能是另一个话题的副本,但是我不明白我的代码在做什么错+我真的很新来回应。我尝试了几种解决方案,但没有一个起作用。我将在这里写一些我读过的帖子:
问题
我需要使用handleInput来记录value
中的字符串
代码
import React, {Component} from 'react';
import Button from './Button';
import Screen from './screen';
import './keyboard.css'
class NumberKeyboard extends Component {
constructor(props){
super(props)
this.state = {
operations: []
}
}
handleInput(props) {
const buttonValue= this.props.value;
console.log(buttonValue)
}
render() {
return (
<div className="keyboard">
<div className="column"></div>
<div className="column">
<div className="keyboardRow roundBorder" value={"example"} onClick={() => this.handleInput('value')}>
<Screen className="crystalScreen"></Screen>
<Button value="clear" >C</Button>
<Button value="±">±</Button>
<Button value=".">.</Button>
<Button value="">+</Button>
</div>
<div className="keyboardRow">
<Button value="clear">1</Button>
<Button value="2">2</Button>
<Button value="3">3</Button>
<Button value="-">-</Button>
</div>
<div className="keyboardRow">
<Button value="4">4</Button>
<Button value="5">5</Button>
<Button value="6">6</Button>
<Button value="*">X</Button>
</div>
<div className="keyboardRow lastRow">
<Button value="7">7</Button>
<Button value="8">8</Button>
<Button value="9">9</Button>
<Button value="%">÷</Button>
</div>
</div>
<div className="column"></div>
</div>
)
}
}
export default NumberKeyboard;
我尝试了几次尝试来解决它,但是每次我得到的最大结果是可悲的未定义或错误。
答案 0 :(得分:1)
您可以使用event
对象。类似的东西:
handleInput = e => {
const buttonValue = e.target.value;
console.log(buttonValue);
//some logic
}
然后您可以在onClick事件上添加方法,并同时传递event
对象。
onClick = {this.handleInput}
答案 1 :(得分:1)
首先,您的按钮当前在被单击时不会执行任何操作,因此我们需要做的是为每个按钮<Button onClick={this.handleInput} value="clear">C</Button>
添加一个onClick。
这会将事件传递给handleInput
。
要获得所单击按钮的值,我们可以这样做:
handleInput(el) {
console.log(el.target.value);
}
答案 2 :(得分:1)
您以错误的方式发送和接收数据。首先,您需要使用onClick={this.handleInput}
或onClick={(e) => this.handleInput(e,'value')}
而不是onClick={() => this.handleInput('value')}
,因为您要在函数中发送'value'
字符串。
<div className="keyboardRow roundBorder" value={"example"} onClick={e => this.handleInput(e, "value")} >
然后通过以下方式接收:
handleInput(e) {
console.log(e.target.value);
}
您可以检查有效的demo。
答案 3 :(得分:1)