如何在没有任何形式的情况下获取 React Js 输入文本值

How to get Reacjs input text value without any form

我是 Reactjs 的新手,这一定是一个简单的问题。我没有找到那个。但它不起作用。可能已经有人问过了

class App extends Component {

constructor() {
    super()
    this.state = {
        currency: '',
        excurrency: '',
        amount: ''
    }
}

<input id='amount' type='text' onChange={(amount) => this.setState({amount})}></input>
<button onClick={ () => alert('show me amount '+this.state.amount)}>amount</button>
}

在我提供一些输入后,我期望它应该为 amount 设置新的值。但是当我单击按钮时,它显示警报为:- 显示数量 [object Object] 为什么它不设置新值?

onClick 回调获取事件对象作为 input/argument 而不是文本值。您需要从该事件对象中获取输入值

<input id='amount' type='text' onChange={(e) => this.setState({ amount: e.target.value })}></input>

您的数据可能在警报触发前尚未更新。 setState 带有回调。

handleChange = (e) => {
this.setState({[e.target.name]:e.target.value}, ()  => {
   console.log(this.state.amount)
}) 
}

<input name='amount' type='text' onChange={e => this.handleChange(e)} />