单击按钮时响应更新输入值

我有一个带有输入字段的 React 组件。


我想在单击按钮时更新输入字段的值,我可以在检查元素时确认该值发生了变化,但它没有显示在输入字段中。下面是一个示例代码,只是为了提供一个想法。


class InputField {

 constructor(props) {

  super(props)

 }

 state = {

  userInput: ''

 }

}


onClick = () => {

 this.setState({

  userInput: 'Test'

 })

}



render() {

 return ( <input value={this.state.userInput} name="sampleInput" />

  <button onClick={this.onClick}> Click me </button>  

 )

}


拉丁的传说
浏览 157回答 3
3回答

芜湖不芜

修复语法你的代码没问题,只是订单很少。我添加了整个组件import React, { Component } from 'react';class InputField extends Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props)&nbsp; }&nbsp; state = {&nbsp; &nbsp; userInput: ''&nbsp; }&nbsp; onClick = () => {&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; userInput: 'Test'&nbsp; &nbsp; })&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <input value={this.state.userInput} name="sampleInput" />&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={this.onClick}>Click me</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )&nbsp; }}export default InputField;

慕妹3242003

我刚刚删除了您示例中的语法错误,它对我有用。import React from 'react';export default class InputField extends React.Component {&nbsp; &nbsp; constructor(props) {&nbsp; &nbsp; &nbsp; &nbsp; super(props)&nbsp; &nbsp; &nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userInput: ''&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; onClick = () => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userInput: 'Test'&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input value={this.state.userInput} name="sampleInput"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick = {this.onClick}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Click me&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript