对不起,如果这个主题可能是另一个主题的副本,但我不明白我的代码做错了什么+我真的很新来react。我尝试了几种解决方案,但没有一个奏效。我会把我读过的一些帖子放在这里:
问题
我需要value
使用 handleInput控制台.log里面的字符串
代码
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;
我尝试了几次尝试来解决它,但每次我得到的最大结果都是可悲的未定义或错误。
- - - - - - - - - - - - - - 更新 - - - - - - - - - - - ---
由于这些帖子的访问,我想进行一些更新并设置一个基于钩子的示例:
import React, { useState } from 'react';
import KeyboardRow from 'src/components/keyboardRow'; /* ideally this
should contain the buttons element. i'm writing in this way just to stay
closer to the initial question */
function NumberKeyboard() {
const [selectedNumber, setSelectedNumber] = useState(0);
const selectNumber = numberSelected => {
setSelectedNumber(numberSelected)
}
return (
<>
<KeyboardRow >
<Button onClick={selectNumber} value="7">7</Button>
<Button onClick={selectNumber} value="8">8</Button>
<Button onClick={selectNumber} value="9">9</Button>
</KeyboardRow >
<div>{selectedNumber}<div>
</>
);
}