[英]React JS How to reset a form
How do I reset the values in a form in React JS onClick?如何在 React JS onClick 中重置表单中的值?
class AddFriendForm extends Component {
constructor(props) {
super(props)
this.state = {
firstname: '',
lastname: '',
}
}
render() {
const { addFriend } = this.props
const setFirstName = add => this.setState({ firstname: add.target.value })
const setLastName = add => this.setState({ lastname: add.target.value })
return (
<div>
<div>
<Label label="First Name" />
<Field onChange={setFirstName} />
<Label label="Last Name" />
<Field onChange={setLastName} />
<SecondaryButton
name="Search"
onClick={() => addFriend(this.state)}
/>
<SecondaryButton
name="Reset"
onClick={() => ???}
/>
</div>
</div>
)
}
}
When the user presses the Reset button, I want an onClick event that resets all the fields in the form to blank.当用户按下重置按钮时,我想要一个 onClick 事件,将表单中的所有字段重置为空白。 Is there a single line of code to do this?是否有一行代码可以做到这一点?
First, create a function called resetForm首先,创建一个名为resetForm的函数
resetForm = () => {
this.setState({
...this.state,
firstname: '',
lastname: ''
})
}
Then trigger the function when reset button is clicked然后在点击重置按钮时触发该功能
onClick={this.resetForm}
Cheers mate队友的欢呼声
EDIT:编辑:
You have to assign the values to "Field" using value={this.state.firstname}您必须使用 value={this.state.firstname} 将值分配给“字段”
<Field value={this.state.firstname} onChange={...
Small tip: dont define your functions in your jsx code.小提示:不要在 jsx 代码中定义函数。
You can do this simply like this.你可以像这样简单地做到这一点。
Before the render()
add below part.在render()
之前添加以下部分。 This is a function to reset the fields.这是一个重置字段的功能。
reset = () => {
this.setState({ firstname: ''})
this.setState({ lastname: ''})
}
And this where the function is called.这就是调用函数的地方。 (In Button onPress
.) (在按钮onPress
。)
<Button
title='reset'
style={styles.button}
onPress={this.reset}
>
</Button>
Note:- use this one in functional component.注意:- 在功能组件中使用这个。
const handleReset = (e) => {
e.preventDefault();
setState(prevState => ({
...prevState,
name: '',
email: '',
password: ''
}))
}
handleReset = () => { setState(({ name: '', email: '', })) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.