【问题标题】:Can't get event.target.value in React无法在 React 中获取 event.target.value
【发布时间】:2020-06-28 12:05:09
【问题描述】:

当我将 onInputChange 函数与 onChange 一起使用时,我试图从 onInputChange 函数中获得反应,但我不明白为什么它不是 console.log 的值。有什么帮助吗?

App.js

import React, { Component } from 'react';
import Output from './Components/Output';
import NumberInput from './Components/NumberInput';
import './App.css';

class App extends Component {
  constructor() {
    super()
    this.state = {
      decimal: 0,
      inputString: ''
    }
  }

  onInputChange = (event) => {
    console.log(event.target.value)
  }

  render() {
    const { decimal, inputString } = this.state;
    return (
      <fragment>
      <h1>Binary to Decimal convertor</h1>
      <NumberInput InputChange={this.onInputChange} />
      <button>Submit</button>
      <Output string={inputString}/>
      </fragment>
      );
  }
}

export default App;

NumberInput 组件:

import React from 'react';

const NumberInput = ({ inputChange }) => {
    return (
            <fragment>
            <input type='search' onChange={inputChange}></input>
            </fragment>
        )
}

export default NumberInput;

【问题讨论】:

    标签: reactjs dom-manipulation


    【解决方案1】:

    需要一些改变

    更改您的InputChange={this.onInputChange}App 组件中的inputChange={this.onInputChange}

    因为您在 NumberInput 组件中访问 inputChange

    并且还要更改您的片段标记,因为您使用 fragment 而不是 Fragment 标记。

    NumberInputApp 组件中使用&lt;Fragment&gt;&lt;React.Fragment&gt;&lt;&gt; 之类的-

    <Fragment>
      <input type='search' onChange={inputChange}></input>
    </Fragment>
    

    【讨论】:

      【解决方案2】:

      InputChange 应该是驼峰式

      改变

      &lt;NumberInput InputChange={this.onInputChange} /&gt;

      &lt;NumberInput inputChange={this.onInputChange} /&gt;

      你可能还需要绑定

      &lt;NumberInput inputChange={(e) =&gt; this.onInputChange(e)} /&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 2021-07-21
        • 1970-01-01
        • 2019-04-12
        • 2019-03-24
        • 1970-01-01
        • 2017-12-22
        相关资源
        最近更新 更多