gpt4 book ai didi

html - 如何在 HTML 标记中显示函数值并通过 addEventListener 单击返回值?

转载 作者:行者123 更新时间:2023-12-03 13:42:34 25 4
gpt4 key购买 nike

我正在尝试构建一个计算器并想在屏幕上打印数字。我还没有输入计算器算法,只是为了在屏幕上打印数字。

const Keys = ({calcKeys})=>(<div className="display-keys"> 
<div className="screen"><handleClick></div>
{calcKeys.map((item)=>{
return <button className="display-keys">{item.key}</button>
})
}
class App extends React.Component { constructor(props) { super(props);
this.state={calcKeys:[{"key": "AC"},{"key": "CE"},{"key": "±"},{"key": "/"},{"key": "7"},{"key": "8"},{"key": "9"},{"key": "x"},{"key": "4"},{"key": "5"},{"key": "6"},{"key": "-"},{"key": "1"},{"key": "2"},{"key": "3"},{"key": "+"},{"key": "."},{"key": "0"}]};}
this.displayKeys = this.displayKeys.bind(this)];
const keyButton = document.querySelector('.display-keys');
handleClick() {
keyButton.addEventListener('click', (e) => {
return const keyPad = e.key;
});
}
render(){
return(
<div className="display-container">
<Keys calcKeys={this.state.calcKeys}/>
</div>
);
}
}
ReactDOM.render( <App />, document.getElementById("root"));

最佳答案

对于这种情况,如果您想单击按钮,则不需要添加 addEventListener

当您使用 React 时,您可以创建一个函数来处理点击。如果您想处理键盘上的按键,则需要使用 addEventListener

我对您的代码进行了一些更改,以使其按预期工作。我没有添加任何逻辑来使计算器工作,但单击任何按钮都会将其添加到状态并显示在“屏幕”上。

这就是我所做的:

// "Keys" Component receives the calcKeys and the handleClick function.
// It uses the handleClick function on the button onClick passing the current item key
const Keys = ({ calcKeys, handleClick }) => (
<div className="display-keys">
{calcKeys.map(item => (
<button onClick={() => handleClick(item.key)}>{item.key}</button>
))}
</div>
)

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
calcKeys: [{"key": "AC"},{"key": "CE"},{"key": "±"},{"key": "/"},{"key": "7"},{"key": "8"},{"key": "9"},{"key": "x"},{"key": "4"},{"key": "5"},{"key": "6"},{"key": "-"},{"key": "1"},{"key": "2"},{"key": "3"},{"key": "+"},{"key": "."},{"key": "0"}],
value: '',
};
this.handleClick = this.handleClick.bind(this)
}

// Here I just receive the key and add it to state.
// This is the place to add logic, check if the key is "AC" for example and clean the state, etc.
handleClick(key) {
const { value } = this.state

this.setState({ value: `${value}${key}` })
}

render() {
const { value } = this.state
return (
<div className="display-container">
<div className="screen">{value}</div>
<Keys calcKeys={this.state.calcKeys} handleClick={this.handleClick} />
</div>
);
}
}

您可以在工作的 JSFiddle 中测试它 here

关于html - 如何在 HTML 标记中显示函数值并通过 addEventListener 单击返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com