函数值如何显示在 HTML 标记中,并带有来自 addEventListerner 单击的返回值?

use*_*297 4 html reactjs

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

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"));
Run Code Online (Sandbox Code Playgroud)

小智 5

对于这种情况,如果您想单击按钮,则无需添加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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处的工作 JSFiddle 中对其进行测试