如何使用alert()允许用户输入其名称并将其保存为状态?
到目前为止,这是我尝试过的事情:
render: function() {
return (
<div>
<input type="text" onChange={ this.handleChange } />
<Button>Save</Button>
</div>
);
}
}
解决方法:
一种选择是使用the prompt()
function,它将显示一个模式对话框,通过该对话框可以输入和获取用户输入. tips()方法还允许您提供自定义问候语,可以将其作为第一个参数传递,如下所示:
const enteredName = prompt('Please enter your name')
可以通过多种方法将其与您现有的react组件集成-一种方法可能如下:
/* Definition of handleClick in component */
handleClick = (event) => {
/* call prompt() with custom message to get user input from alert-like dialog */
const enteredName = prompt('Please enter your name')
/* update state of this component with data provided by user. store data
in 'enteredName' state field. calling setState triggers a render of
this component meaning the enteredName value will be visible via the
updated render() function below */
this.setState({ enteredName : enteredName })
}
render: function() {
return (
<div>
{/* For demonstration purposes, this is how you can render data
previously entered by the user */ }
<p>Previously entered user name: { this.state.enteredName }</p>
<input type="text" onChange={ this.handleChange } />
<input
type="button"
value="Alert the text input"
onClick={this.handleClick}
/>
</div>
);
}
});