设置反应状态后如何清除输入值?

时间:2019-04-22 08:54:18

标签: reactjs

我正在做一个待办事项应用程序,在提交用户的输入后,我在数据库中发出发布请求以进行更新,然后更新状态。然后我试图使用清除输入字段 e.target.value =“”。但这是行不通的。我对JS和React非常陌生。有人可以指出我在这里做错了吗。

class TodoApp extends Component {
    constructor(props) {
        super(props);

        this.state = {
            todos: [],
        };`enter code here

        this.handleTodos = this.handleTodos.bind(this);
        this.handleLogout = this.handleLogout.bind(this);
        this.removeTodo = this.removeTodo.bind(this);
    };

    componentDidMount() {

        const authStr = 'Bearer ' + getJWTToken();

        axios.get('/tasks', {
            'headers': {
                'Authorization': authStr
            }
        }).then(res => {
            // console.log(res.data);
            this.setState({
                todos: res.data,
            })
        }).catch(err => {
            console.log(err);
        });

    };

    removeTodo = id => {
        //  console.log(id)

        const authStr = 'Bearer ' + getJWTToken();

        axios.delete('/tasks/' + id, {
            'headers': {
                'Authorization': authStr
            }
        }).then(res => {
            // console.log(res.data);
            let newTodos = [...this.state.todos];

            newTodos = newTodos.filter(todo => {
                return todo._id !== id;
            });

            //Update the State
            this.setState({
                todos: newTodos
            });
        }).catch(err => {
            console.log(err);
        });

    };

    handleTodos = e => {

        e.preventDefault();
        const authStr = 'Bearer ' + getJWTToken();

        var todo = {
            description: e.target.value
        }

        console.log(todo)

        axios.post('/tasks', todo, {
            'headers': {
                'Authorization': authStr
            }
        }).then(res => {
            // console.log(res.data);
            this.setState({
                todos: this.state.todos.concat(res.data)
            })
        }).catch(err => {
            console.log(err)
        });

        e.target.value = "";
        // console.log(todo);
    };

    handleLogout() {
        localStorage.removeItem('jwtToken');
        this.props.history.push("/");
    }

    render() {

        const listLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span: 8 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 16 },
            },
          };      

        return (
            <div className="container-fluid App">
                <div className="todoContainer">
                    <Header
                        handleLogout={this.handleLogout}
                    />

                    <h1 style={{ paddingTop: "10px" }}>TODO App</h1>

                    <Input
                        placeholder="What needs to be done?"
                        onPressEnter={this.handleTodos}
                    />

                    <List
                        itemLayout="horizontal"
                        locale={{ emptyText: "No Todos" }}
                        dataSource={this.state.todos}
                        renderItem={item => (
                            <TodoItem
                                todo={item}
                                removeTodo={this.removeTodo}
                            />
                        )}
                    />

                </div>
            </div>
        );
    };

};

export default TodoApp;

4 个答案:

答案 0 :(得分:0)

您应该将输入字段的值绑定到您的状态以正确控制它。您可以这样修改状态声明:

this.state = {
    todos: [],
    whatToDo: ""
}

并将您的输入字段绑定到您的状态,如下所示:

<Input
    placeholder="What needs to be done?"
    onPressEnter={this.handleTodos}
    value={this.state.whatToDo}
    onChange={this.onInputChange} // will update the state on each change
/>

然后创建onInputChange函数:

onInputChange= (event, data) => {
    this.setState({ whatToDo: data.value });
}

最后,更改行

e.target.value = "";

this.setState({ whatToDo: "" });

答案 1 :(得分:0)

尝试一下

  handleTodos = e => {

        e.preventDefault();
        const authStr = 'Bearer ' + getJWTToken();

        var todo = {
            description: e.target.value
        }

        console.log(todo)

        axios.post('/tasks', todo, {
            'headers': {
                'Authorization': authStr
            }
        }).then(res => {
            // console.log(res.data);
            this.setState({
                todos: this.state.todos.concat(res.data)
            })
        }).catch(err => {
            console.log(err)
        });
        //RESET FIELD
        e.target.reset()
    };

答案 2 :(得分:0)

您可以使用Ref清除输入文本。这是可行的解决方案。此外,请点击此Reactjs链接以获取更多信息。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      inputField: ""
    };
  }
  keyHandler = event => {
    if (event.key === "Enter") {
      console.log(this.inputRef.current.value);
      this.setState({ inputField: event.target.value });
      this.inputRef.current.value = "";
    }
  };
  render() {
    return (
      <div>
        <input
          type="text"
          onKeyPress={this.keyHandler}
          ref={this.inputRef}
        />
        <p>{this.state.inputField}</p>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>

答案 3 :(得分:0)

请允许我告诉您,这通常不是输入操作的反应方式。我也可以尝试解决您的错误,但我更愿意带您走上正确的道路。看看此文档页面:https://reactjs.org/docs/forms.html

尤其是这个stackoverflow答案:What are controlled components and uncontrolled components in ReactJS?

使用受控组件,要清除输入字段,只需调用setState清空特定状态变量的内容即可。请看一下我要编写的示例:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};
  }

  handleChange = (event) => {
    this.setState({value: event.target.value});
  }

  handleSubmit = (event) => {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  emptyInput = () => {
    alert('Emptying input');
    this.setState({ value: '' });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
        <button onClick={emptyInput}>Empty input</button>
      </form>
    );
  }
}