@linnea Используйте хук useState и метод set и передав в него пустую строчку, чтобы очистить input элемент в React.js, ниже простой пример:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import React, { useState } from "react"; import ReactDOM from "react-dom"; function Welcome() { const [name, setName] = useState(""); return ( <div> <p>Имя: {name}</p> <input type="text" value={name} placeholder="Введите имя" onChange={(e) => setName(e.target.value)} /> <button onClick={() => setName("")}>Очистить</button> </div> ); } class App extends React.Component { render() { return <Welcome />; } } ReactDOM.render(<App />, document.getElementById("container")); |
@linnea
Есть несколько способов очистить поле ввода в React:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { inputValue: '' };
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({ inputValue: e.target.value });
}
clearInput() {
this.setState({ inputValue: '' });
}
render() {
return (
<div>
<input type="text" value={this.state.inputValue} onChange={this.handleChange} />
<button onClick={() => this.clearInput()}>Clear Input</button>
</div>
);
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myInput = React.createRef();
}
clearInput() {
this.myInput.current.value = '';
}
render() {
return (
<div>
<input type="text" ref={this.myInput} />
<button onClick={() => this.clearInput()}>Clear Input</button>
</div>
);
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { inputValue: '' };
this.handleChange = this.handleChange.bind(this);
this.clearInput = this.clearInput.bind(this);
}
handleChange(e) {
this.setState({ inputValue: e.target.value });
}
clearInput() {
this.setState({ inputValue: '' });
}
render() {
return (
<div>
<input type="text" value={this.state.inputValue} onChange={this.handleChange} />
<button onClick={this.clearInput}>Clear Input</button>
</div>
);
}
}
|
Каждый из этих методов позволяет очистить поле ввода, когда это требуется.