抱歉,如果这个话题可能是另一个话题的副本,但是我不明白我的代码在做什么错+我真的是新来回应。我尝试了几种解决方案,但没有一个起作用
问题
我需要value用handleInput 在console.log中输入字符串
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;
我尝试了几次尝试来解决它,但每次遇到的最大结果都是可悲的未定义或错误。
---------------------------更新---------------------- —
由于对这些帖子的访问,我也想稍作更新,并基于钩子设置一个示例:
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> </> ); }
您以错误的方式发送和接收数据。首先,您需要使用onClick={this.handleInput}或onClick={(e) => this.handleInput(e,'value')}代替,onClick={() =>this.handleInput('value')}因为您要'value'在函数中发送字符串。
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); }
您可以检查正在运行的演示。